【问题标题】:How to get the row index of 2D Array?如何获取二维数组的行索引?
【发布时间】:2017-06-13 12:27:54
【问题描述】:

我是 Swift 新手,我正在使用 2D 数组进行比较,一旦条件为真,我需要获取行索引,但我得到了一个错误状态 cannot invoke index with an argument list of type (of:Array<Float>)

我的代码:

var entryCoordinate: [[Float]] = [[130.6,61.0],[167.5,61.0],[204.5,61.0],[243.6,61.0],[281.16,61.0],[315.3,61.0]]

 for indexs in entryCoordinate
        {
            if indexs[0] == startPathPointX && indexs[1] == startPathPointY
            {
                let pathStartElement = indexs.index(of: indexs)
                print(pathStartElement)
            }

            if indexs[0] == endPathPointX && indexs[1] == endPathPointY
            {
                let pathEndElement = indexs.index(of: indexs)
                print(pathEndElement)
            }
        }

【问题讨论】:

  • indexs.index(of: indexs) 你的意思是entryCoordinate.index(of: indexs),不是吗?否则,如果您有重复值,它应该只返回找到的第一个元素。还有if indexs[0] == startPathPointX && indexs[1] == startPathPointY,不是吗?
  • 是的,如果发现我想获取 entryCoordinate 的行索引...所以这就像获取值所在的行
  • for (index, aCoordindate) in entryCoordinate.enumerated() { if aCoordindate[0] == startX && aCoordindate[1] == startY { print("CoordinateFound: \(aCoordindate)"); print("Index: \(index)") } }?从那里获取索引的 For 循环:*.com/questions/24028421/…

标签: ios arrays swift multidimensional-array swift3


【解决方案1】:

从带有startPathPointYendPathPointY 的代码中,您需要比较二维数组中的第二个对象,但您会继续比较第一个对象,并且您可以像这样将index(where:) 与您的数组一起使用以获得pathStartElementpathEndElement.

if let pathStartElement = entryCoordinate.index(where: { $0[0] == startPathPointX && $0[1] == startPathPointY }) {
    print(pathStartElement)
}
if let pathEndElement = entryCoordinate.index(where: { $0[0] == endPathPointX && $0[1] == endPathPointY }) {
    print(pathEndElement)
}

【讨论】:

    【解决方案2】:

    试试这个代码:

    let myIndexPathStartElement = self.arrImagetData.index(where: { $0[0] == startPathPointX && $0[1] == startPathPointY })
    
    let myIndexPathEndElement = self.arrImagetData.index(where: { $0[0] == endPathPointX && $0[1] == endPathPointY })
    

    【讨论】:

      最近更新 更多