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 中查找列表项的索引?


- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01