我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
当前回答
只需使用firstIndex方法。
array.firstIndex(where: { $0 == searchedItem })
其他回答
在Swift 4中,如果你正在遍历你的DataModel数组,确保你的数据模型符合Equatable Protocol,实现lhs=rhs方法,只有这样你才能使用”。指数(“。例如
class Photo : Equatable{
var imageURL: URL?
init(imageURL: URL){
self.imageURL = imageURL
}
static func == (lhs: Photo, rhs: Photo) -> Bool{
return lhs.imageURL == rhs.imageURL
}
}
然后,
let index = self.photos.index(of: aPhoto)
如果你还在使用Swift 1.x
然后尝试,
let testArray = ["A","B","C"]
let indexOfA = find(testArray, "A")
let indexOfB = find(testArray, "B")
let indexOfC = find(testArray, "C")
在Swift 4/5中,使用“firstIndex”查找索引。
let index = array.firstIndex{$0 == value}
对于自定义类,您需要实现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中,可以使用firstIndex方法。使用==相等操作符根据id在数组中查找对象的示例:
let index = array.firstIndex{ $0.id == object.id }
注意,这个解决方案避免了您的代码需要符合公平协议,因为我们比较的是属性而不是整个对象
另外,关于== vs ===的注意事项,因为到目前为止发布的许多答案在用法上有所不同:
==是相等运算符。它检查值是否相等。 ===是恒等运算符。它检查一个类的两个实例是否指向同一个内存。这与相等不同,因为使用相同值独立创建的两个对象使用==被认为是相等的,而不是===,因为它们是不同的对象。(源)
从Swift的文档中阅读更多关于这些运营商的信息是值得的。