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

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


当前回答

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.   
}

其他回答

以防有人遇到这种问题

Cannot invoke initializer for type 'Int' with an argument list of type '(Array<Element>.Index?)'

一定要这么做

extension Int {
    var toInt: Int {
        return self
    }
}

then

guard let finalIndex = index?.toInt else {
    return false
}

这些方法对我都适用

这是我对Swift 4的解决方案:

let monday = Day(name: "M")
let tuesday = Day(name: "T")
let friday = Day(name: "F")

let days = [monday, tuesday, friday]

let index = days.index(where: { 
            //important to test with === to be sure it's the same object reference
            $0 === tuesday
        })

斯威夫特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更新:

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)