如何找到斯威夫特列表项的指数? [英] How to find index of list item in Swift?

查看:135
本文介绍了如何找到斯威夫特列表项的指数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过搜索列表中找到一个项目索引。是否有人知道如何做到这一点?

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​​,阵列斩获发现使用 Col​​lectionType (<其中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找到的第一个元素是由另一部分支持 Col​​lectionType

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆