1

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

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, should be enumerate for 2.3 :-)
1

Functional approach:

let items = [["0, 0", "0, 1"], ["1, 0", "1, 1", "1, 2"]]
items.enumerated().forEach { (firstDimIndex, firstDimItem) in
    firstDimItem.enumerated().forEach({ (secondDimIndex, secondDimItem) in
        print("item: \(secondDimItem), is At Index: [\(firstDimIndex), \(secondDimIndex)]")
    })
}

prints:

item: 0, 0, is At Index: [0, 0]

item: 0, 1, is At Index: [0, 1]

item: 1, 0, is At Index: [1, 0]

item: 1, 1, is At Index: [1, 1]

item: 1, 2, is At Index: [1, 2]

Comments

0

I wouldn't use a for loop, I would do something like this:

import Foundation

var playing = [["one", "two"], ["three", "four"]]

if let index = playing.index(where: { $0.contains("two") }) {
  print(index)
} else {
  print("Not found")
}

This prints:

0

Or to get the entire subarray containing what you want:

if let subarray = playing.first(where: { $0.contains("three") }) {
  print(subarray)
} else {
  print("Not found")
}

Prints:

["three", "four"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.