arrays - 用于搜索数组的 for 循环,Swift
问题描述
我需要在对象数组中搜索特定值。
swift中是否有与for(Distance d : distances)
Java等效的功能。
解决方案
你可以使用类似下面的东西
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 将给出匹配对象的第一个索引。
推荐阅读
- python - 用于缩略图和端屏自动化的 Youtube API
- reactjs - reactjs如何从POST请求对象访问表单数据
- python - 插入图像 tkinter
- python - 如何使用子进程来完成复杂的交互式 shell 脚本
- react-native - 如何解决这个问题?navigation.navigate 不是函数
- typescript - 打字稿不能扩展 Autodesk.Viewing.ToolInterface
- android - Flutter 仅在设备 (Android) 连接时在后台运行(屏幕关闭)
- hyperledger-fabric - 文件包含 goimports 错误
- r - 为什么 stat_compare_means 只在一个方面显示成对比较?
- mysql - 从选择 Laravel 中选择