Jonnny
Jonnny

Reputation: 5039

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

Upvotes: 1

Views: 58

Answers (3)

GetSwifty
GetSwifty

Reputation: 7746

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]

Upvotes: 1

i_am_jorf
i_am_jorf

Reputation: 54600

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"]

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

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

Upvotes: 3

Related Questions