我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
当前回答
斯威夫特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)
对于SWIFT 3,您可以使用一个简单的函数
func find(objecToFind: String?) -> Int? {
for i in 0...arrayName.count {
if arrayName[i] == objectToFind {
return i
}
}
return nil
}
这将给出数字的位置,所以你可以用like
arrayName.remove(at: (find(objecToFind))!)
希望对你有用
斯威夫特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)
你可以用闭包来过滤数组:
var myList = [1, 2, 3, 4]
var filtered = myList.filter { $0 == 3 } // <= returns [3]
你可以对数组进行计数:
filtered.count // <= returns 1
所以你可以通过组合这些来确定数组是否包含你的元素:
myList.filter { $0 == 3 }.count > 0 // <= returns true if the array includes 3
如果你想找这个职位,我不认为有什么花哨的方法,但你可以这样做:
var found: Int? // <= will hold the index if it was found, or else will be nil
for i in (0..x.count) {
if x[i] == 3 {
found = i
}
}
EDIT
当我们这样做的时候,为了一个有趣的练习,让我们扩展Array来有一个find方法:
extension Array {
func find(includedElement: T -> Bool) -> Int? {
for (idx, element) in enumerate(self) {
if includedElement(element) {
return idx
}
}
return nil
}
}
现在我们可以这样做:
myList.find { $0 == 3 }
// returns the index position of 3 or nil if not found
在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)