简体   繁体   English

如何获取具有匹配特定条件的属性值的数组中对象的索引?

[英]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. 现在,我们有一个名为“ markers”的数组,其中包含10个标记对象,并且所有属性都已初始化。 How can I find the index of the marker item whose coordinate value matches the value of someCoordinate? 如何找到其坐标值与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. 在尝试以下iosdk的建议时,我发现我正在尝试比较marker.coordinate属性,它是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: 或者,在Swift 1上,indexOf函数可以是:

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?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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