0

I am new to Swift and I am using a 2D array for comparing and I need to get the row index once the condition is true but I got an error state that cannot invoke index with an argument list of type (of:Array<Float>)

My Code:

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)` you meant `entryCoordinate.index(of: indexs)`, no? Else, if you have duplicates values, it should returns only the first elements found. Also `if indexs[0] == startPathPointX && indexs[1] == startPathPointY`, no? – Larme Jun 13 '17 at 12:30
  • yup if found i want to get the row index of entryCoordinate...so it is like getting which row is the value located – kuhandran samudra pandiyan Jun 13 '17 at 12:32
  • `for (index, aCoordindate) in entryCoordinate.enumerated() { if aCoordindate[0] == startX && aCoordindate[1] == startY { print("CoordinateFound: \(aCoordindate)"); print("Index: \(index)") } }` instead? For Loop with Index taken from there: https://stackoverflow.com/questions/24028421/swift-for-loop-for-index-element-in-array – Larme Jun 13 '17 at 12:37

2 Answers2

0

From your code with startPathPointY and endPathPointY you need to compare the second object from 2D array but you keep comparing the first one and you con use index(where:) with your array like this to get the pathStartElement and pathEndElement.

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)
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
0

Try this code:

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

let myIndexPathEndElement = self.arrImagetData.index(where: { $0[0] == endPathPointX && $0[1] == endPathPointY })
Garima Saini
  • 173
  • 8