我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
当前回答
斯威夫特4。如果数组包含类型为[String: AnyObject]的元素。因此,要查找元素的索引,请使用下面的代码
var array = [[String: AnyObject]]()// Save your data in array
let objectAtZero = array[0] // get first object
let index = (self.array as NSArray).index(of: objectAtZero)
或者如果你想找到索引的基础上的关键字从字典。这里数组包含对象的模型类和我匹配id属性。
let userId = 20
if let index = array.index(where: { (dict) -> Bool in
return dict.id == userId // Will found index of matched id
}) {
print("Index found")
}
OR
let storeId = Int(surveyCurrent.store_id) // Accessing model key value
indexArrUpTo = self.arrEarnUpTo.index { Int($0.store_id) == storeId }! // Array contains models and finding specific one
其他回答
对于自定义类,您需要实现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的文档中阅读更多关于这些运营商的信息是值得的。
在Swift 2 (Xcode 7)中,Array包含了一个由CollectionType协议提供的indexOf方法。(实际上,有两个indexOf方法——一个使用相等来匹配参数,另一个使用闭包。)
在Swift 2之前,泛型类型(如集合)无法为从它们派生的具体类型(如数组)提供方法。所以,在Swift 1中。X, index of是一个全局函数…它也被重新命名了,所以在Swift 1中。X,这个全局函数叫做find。
这也是可能的(但不是必要的)使用indexOfObject方法从NSArray…或者其他任何来自基金会的更复杂的搜索方法,这些方法在Swift标准库中没有等价物。只需导入Foundation(或另一个传递导入Foundation的模块),将数组转换为NSArray,就可以使用NSArray上的许多搜索方法。
您还可以使用函数库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)