我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
当前回答
在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)
其他回答
您还可以使用函数库Dollar在数组上执行indexOf,例如http://www.dollarswift.org/#indexof-indexof
$.indexOf([1, 2, 3, 1, 2, 3], value: 2)
=> 1
斯威夫特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 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)
斯威夫特4
假设你想从名为cardButtons的数组中存储一个数字到cardNumber中,你可以这样做:
let cardNumber = cardButtons.index(of: sender)
Sender是按钮的名称
对于自定义类,您需要实现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)