【问题标题】:Geting object from array of array and it's array number从数组数组及其数组编号中获取对象
【发布时间】:2016-11-08 19:25:00
【问题描述】:

我正在使用 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

我希望能够打印出该对象属于哪个数组,然后使用该当前对象

【问题讨论】:

    标签: swift swift2


    【解决方案1】:

    使用enumerated() 将索引和元素配对,如下所示:

    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
    

    【讨论】:

    • 谢谢,2.3 应该是 enumerate :-)
    【解决方案2】:

    功能方法:

    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, is At Index: [0, 0]

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

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

    项目:1, 1,位于索引:[1, 1]

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

    【讨论】:

      【解决方案3】:

      我不会使用 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")
      }
      

      打印:

      [“三”,“四”]

      【讨论】:

        猜你喜欢
        • 2019-11-14
        • 1970-01-01
        • 2017-10-06
        • 2022-01-23
        • 1970-01-01
        • 2021-08-22
        • 1970-01-01
        • 2016-04-15
        • 1970-01-01
        相关资源
        最近更新 更多