ios - 如何获取属性值符合特定条件的数组中对象的索引?

标签 ios swift

也许这个问题之前已经有人回答过,或者答案很明显,但我已经搜索了好几天都找不到这个问题的答案。如果我对此束手无策,我将不胜感激。

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

let someCoordinate = CLLocationCoordinate2DMake(someLatitude, someLongitude)

现在假设我有一个名为“markers”的数组,包含 10 个所有属性都已初始化的标记对象。如何找到坐标值与 someCoordinate 值匹配的标记项的索引?

编辑

在尝试 iosdk 的建议时下面,我发现我正在尝试比较 marker.coordinate 属性,它是一个 CLLocationCoordinate2D。那没有像我预期的那样工作。相反,我尝试了这个并且它起作用了:

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?

或者,在 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
}

然后将上面的最后一行替换为:

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

关于ios - 如何获取属性值符合特定条件的数组中对象的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31138216/

相关文章:

ios - 无法在 iOS7 中使用自定义 RGBa 设置 barTintColor

ios - 如何调试 NSAllowsArbitraryLoads 不起作用?

ios - UIAlert 关闭后恢复 session

iOS - 下载动态字体

objective-c - 在 Objective-C 中,我们是否必须使用 self.var 或仅使用 var 来引用 self 的属性?

objective-c - 使用 NIPagingScrollView 使 3 个 View 可见?

ios - 面向协议(protocol)的编程不会带来继承主要解决的代码重复问题吗?

swift - ViewDidLoad() 中的导航栏高度未以编程方式更改?

ios - 如何在应用程序委托(delegate)之外注册本地通知?

swift - 将数组数据加载到 TableView 中