我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?

我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。


当前回答

For (>= swift 4.0)

这相当简单。 考虑下面的Array对象。

var names: [String] = ["jack", "rose", "jill"]

为了得到元素rose的索引,你所要做的就是:

names.index(of: "rose") // returns 1

注意:

Array.index(of:)返回一个可选值<Int值>。 Nil表示元素不存在于数组中。 您可能希望强制打开返回值,或者使用if-let来绕过可选选项。

其他回答

斯威夫特2.1

var array = ["0","1","2","3"]

if let index = array.indexOf("1") {
   array.removeAtIndex(index)
}

print(array) // ["0","2","3"]

斯威夫特3

var array = ["0","1","2","3"]

if let index = array.index(of: "1") {
    array.remove(at: index)
}
array.remove(at: 1)

在Swift 2 (Xcode 7)中,Array包含了一个由CollectionType协议提供的indexOf方法。(实际上,有两个indexOf方法——一个使用相等来匹配参数,另一个使用闭包。)

在Swift 2之前,泛型类型(如集合)无法为从它们派生的具体类型(如数组)提供方法。所以,在Swift 1中。X, index of是一个全局函数…它也被重新命名了,所以在Swift 1中。X,这个全局函数叫做find。

这也是可能的(但不是必要的)使用indexOfObject方法从NSArray…或者其他任何来自基金会的更复杂的搜索方法,这些方法在Swift标准库中没有等价物。只需导入Foundation(或另一个传递导入Foundation的模块),将数组转换为NSArray,就可以使用NSArray上的许多搜索方法。

对于自定义类,您需要实现Equatable协议。

import Foundation

func ==(l: MyClass, r: MyClass) -> Bool {
  return l.id == r.id
}

class MyClass: Equtable {
    init(id: String) {
        self.msgID = id
    }

    let msgID: String
}

let item = MyClass(3)
let itemList = [MyClass(1), MyClass(2), item]
let idx = itemList.indexOf(item)

printl(idx)

由于swift在某些方面比面向对象的函数性更强(数组是结构体,而不是对象),使用函数"find"对数组进行操作,返回一个可选值,所以准备好处理nil值:

let arr:Array = ["a","b","c"]
find(arr, "c")!              // 2
find(arr, "d")               // nil

使用firstIndex和lastIndex -这取决于你是在寻找项目的第一个索引还是最后一个索引:

let arr = ["a","b","c","a"]

let indexOfA = arr.firstIndex(of: "a") // 0
let indexOfB = arr.lastIndex(of: "a") // 3

在Swift 4.2中

.index(where:)被更改为.firstIndex(where:)

array.firstIndex(where: {$0 == "person1"})