简体   繁体   中英

How can I get the index of an object in an array with a property value that matches a specific criteria?

Maybe this question has already been answered before or the answer is so obvious but I've been searching for days and cannot find an answer to this problem. I would appreciate any help on this as I'm at my wits' end.

class marker {
    var latitude = Double()
    var longitude = Double()
    var coordinate = CLLocationCoordinate2DMake(latitude, longitude)
}

let someCoordinate = CLLocationCoordinate2DMake(someLatitude, someLongitude)

Now let's say that I have an array named "markers" of 10 marker objects with all properties already initialized. How can I find the index of the marker item whose coordinate value matches the value of someCoordinate?

EDIT

While trying out the suggestion of iosdk below, I found out that I was trying to compare the marker.coordinate property which is a CLLocationCoordinate2D. That did not work as I expected. Instead I tried this and it worked:

let markerIndex = indexOfMarker(markers) { $0.position.latitude == latitude && $0.position.longitude == longitude }
struct SomeStruct {
  let a, b: Int
}

let one = SomeStruct(a: 1, b: 1)
let two = SomeStruct(a: 2, b: 2)
let three = SomeStruct(a: 3, b: 3)

let ar = [one, two, three]

let ans = ar.indexOf { $0.a == 2 } // 1?

Or, on Swift 1, the indexOf function can be:

func indexOfOld<S : SequenceType>(seq: S, predicate: S.Generator.Element -> Bool) -> Int? {

  for (index, value) in enumerate(seq) {
    if predicate(value) {
      return index
    }
  }
  return nil
}

And you'd replace the last line above with:

let ans = indexOfOld(ar) { $0.a == 2 } // 1?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM