如何找到斯威夫特列表项的指数? [英] How to find index of list item in Swift?
问题描述
我想通过搜索列表中找到一个项目索引。是否有人知道如何做到这一点?
I am trying to find an item index by searching a list. Does anybody know how to do that?
我看到有list.StartIndex和list.EndIndex BU我想是Python的list.index(文本)
I see there is list.StartIndex and list.EndIndex bu I want something like python's list.index("text")
推荐答案
由于SWIFT是在某些方面更多的功能比(与数组是结构,而不是对象)面向对象的,使用功能找到磁盘阵列上运行,它返回一个可选值,所以ppared处理一个零值$ p $:
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
更新雨燕2.0:
的旧找到
功能不支持任何更多的雨燕2.0!的
The old find
function is not supported any more with Swift 2.0!
随着雨燕2.0,阵列
斩获发现使用 CollectionType $ C的扩展定义的函数的元素的索引能力$ C>(<其中code>阵列
工具):
With Swift 2.0, Array
gains the ability to find the index of an element using a function defined in an extension of CollectionType
(which Array
implements):
let arr = ["a","b","c"]
let indexOfA = arr.indexOf("a") // 0
let indexOfB = arr.indexOf("b") // 1
let indexOfD = arr.indexOf("d") // nil
此外,在数组中履行一个predicate找到的第一个元素是由另一部分支持 CollectionType
:
Additionally, finding the first element in an array fulfilling a predicate is supported by another extension of CollectionType
:
let arr2 = [1,2,3,4,5,6,7,8,9,10]
let indexOfFirstGreaterThanFive = arr2.indexOf({$0 > 5}) // 5
let indexOfFirstGreaterThanOneHundred = arr2.indexOf({$0 > 100}) // nil
请注意,这两个函数返回可选的值,如找到
以前那样。
Note that these two functions return optional values, as find
did before.
这篇关于如何找到斯威夫特列表项的指数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!