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

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


当前回答

在Swift 4.2中

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

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

其他回答

Swift 2更新:

sequence.contains(element):如果给定序列(如 数组)包含指定的元素。

斯威夫特1:

如果你只是检查一个元素是否包含在一个数组中,也就是说,只是获取一个布尔指示符,使用contains(sequence, element)而不是find(array, element):

contains(sequence, element):如果给定序列(如 数组)包含指定的元素。

请看下面的例子:

var languages = ["Swift", "Objective-C"]
contains(languages, "Swift") == true
contains(languages, "Java") == false
contains([29, 85, 42, 96, 75], 42) == true
if (contains(languages, "Swift")) {
  // Use contains in these cases, instead of find.   
}

对于自定义类,您需要实现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 4.2中

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

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

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)