首页 > 解决方案 > 用于搜索数组的 for 循环,Swift

问题描述

我需要在对象数组中搜索特定值。
swift中是否有与for(Distance d : distances)Java等效的功能。

标签: arraysswift

解决方案


你可以使用类似下面的东西

let arr = [1,2,3,4,5]
let index = arr.firstIndex(of: 3)

index 将给出匹配对象的第一个索引。它还有其他变化。在此处查看更多详细信息 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 })

index 将给出匹配对象的第一个索引。


推荐阅读