How to find index of list item in Swift?(如何在 Swift 中查找列表项的索引?)
问题描述
我正在尝试通过搜索 list 来查找 item index.有人知道该怎么做吗?
I am trying to find an item index by searching a list. Does anybody know how to do that?
我看到有 list.StartIndex 和 list.EndIndex 但我想要类似 python 的 list.index("text") 的东西.
I see there is list.StartIndex and list.EndIndex but I want something like python's list.index("text").
推荐答案
由于 swift 在某些方面比面向对象更具功能性(并且数组是结构,而不是对象),所以使用函数find";对数组进行操作,它返回一个可选值,所以准备处理一个 nil 值:
As swift is in some regards more functional than object-oriented (and Arrays are structs, not objects), use the function "find" to operate on the array, which returns an optional value, so be prepared to handle a nil value:
let arr:Array = ["a","b","c"]
find(arr, "c")! // 2
find(arr, "d") // nil
使用 firstIndex 和 lastIndex - 取决于您要查找项目的第一个索引还是最后一个索引:
Use firstIndex and lastIndex - depending on whether you are looking for the first or last index of the item:
let arr = ["a","b","c","a"]
let indexOfA = arr.firstIndex(of: "a") // 0
let indexOfB = arr.lastIndex(of: "a") // 3
这篇关于如何在 Swift 中查找列表项的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Swift 中查找列表项的索引?
基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
