Jonnny Jonnny - 26 days ago 10
Swift Question

Geting object from array of array and it's array number

I'm using Swift 2.3 and I have the following type array of arrays of my custom object called

Player


`var playing = [[obj-one, obj-two],[obj-three, obj-four]]`


How would I use a for-in loop or something else so I can get the array index and the object?

I have the following:

for (index, p) in playing { -- Expression type [[Player]] is ambigious


I've also tried

for in (index, p: Player) in playing { -- same result.


and

for in (index, p) in playing as! Player { -- doesn't conform to squence type


I want to just be able to print out which array the object belongs to and then work with that current object

Answer

Use enumerated() to pair up an index and an element, like this:

let a = [["hello", "world"], ["quick", "brown", "fox"]]
for outer in a.enumerated() {
    for inner in outer.element.enumerated() {
        print("array[\(outer.offset)][\(inner.offset)] = \(inner.element)")
    }
}

This produces the following output:

array[0][0] = hello
array[0][1] = world
array[1][0] = quick
array[1][1] = brown
array[1][2] = fox
Comments