【发布时间】:2019-05-03 01:47:47
【问题描述】:
我需要在对象数组中搜索特定值。
swift中是否有相当于Java中for(Distance d : distances)的功能。
【问题讨论】:
我需要在对象数组中搜索特定值。
swift中是否有相当于Java中for(Distance d : distances)的功能。
【问题讨论】:
你指的是for-in循环吗?
let distances = [1, 2, 3, 4, 5]
for distance in distances {
if distance == something {
// do something
break
}
}
希望对你有帮助!
【讨论】:
你可以使用类似下面的东西
let arr = [1,2,3,4,5]
let index = arr.firstIndex(of: 3)
索引将给出匹配对象的第一个索引。 它还有其他变化。 在这里查看更多详情 https://developer.apple.com/documentation/swift/array/1848165-first
更新:特定于您的查询
struct Test {
let number: Int
}
let arr = [Test(number: 1),Test(number: 2),Test(number: 3),Test(number: 4),Test(number: 5)]
let index = arr.firstIndex(where: {$0.number == 4 })
索引将给出匹配对象的第一个索引。
【讨论】: