从数组数组中获取对象及其数组编号

时间:2016-11-08 19:25:01

标签: swift swift2

我使用的是Swift 2.3,我有一个名为Player的自定义对象的以下类型的数组数组

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

我如何使用for-in循环或其他东西以便我可以获取数组索引和对象?

我有以下内容:

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

我也试过

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

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

我希望能够打印出对象所属的数组,然后使用当前对象

3 个答案:

答案 0 :(得分:3)

使用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)") } } 配对索引和元素,如下所示:

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

这会产生以下输出:

var data  = ["004", "456", "333", "555"];

答案 1 :(得分:1)

功能方法:

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

打印:

  

item:0,0,at Index:[0,0]

     

item:0,1,at Index:[0,1]

     

item:1,0,at Index:[1,0]

     

项目:1,1是在索引:[1,1]

     

项目:1,2,在索引:[1,2]

答案 2 :(得分:0)

我不会使用for循环,我会做这样的事情:

import Foundation

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

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

打印:

  

0

或者让整个子阵列包含您想要的内容:

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

打印:

  

[“三”,“四”]