我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
当前回答
For (>= swift 4.0)
这相当简单。 考虑下面的Array对象。
var names: [String] = ["jack", "rose", "jill"]
为了得到元素rose的索引,你所要做的就是:
names.index(of: "rose") // returns 1
注意:
Array.index(of:)返回一个可选值<Int值>。 Nil表示元素不存在于数组中。 您可能希望强制打开返回值,或者使用if-let来绕过可选选项。
其他回答
tl; diana:
对于课程,你可能会寻找:
let index = someArray.firstIndex{$0 === someObject}
完整的回答:
我认为值得一提的是,对于引用类型(类),你可能想要执行一个标识比较,在这种情况下,你只需要在谓词闭包中使用===标识操作符:
Swift 5、Swift 4.2:
let person1 = Person(name: "John")
let person2 = Person(name: "Sue")
let person3 = Person(name: "Maria")
let person4 = Person(name: "Loner")
let people = [person1, person2, person3]
let indexOfPerson1 = people.firstIndex{$0 === person1} // 0
let indexOfPerson2 = people.firstIndex{$0 === person2} // 1
let indexOfPerson3 = people.firstIndex{$0 === person3} // 2
let indexOfPerson4 = people.firstIndex{$0 === person4} // nil
注意,上面的语法使用了尾随闭包语法,等价于:
let indexOfPerson1 = people.firstIndex(where: {$0 === person1})
Swift 4 / Swift 3 -该函数过去被称为index
Swift 2 -该函数过去被称为indexOf
*请注意paulbailey关于实现Equatable的类类型的相关和有用的评论,其中您需要考虑是否应该使用===(标识操作符)或==(相等操作符)进行比较。如果您决定使用==进行匹配,那么您可以简单地使用其他人(人们)建议的方法。firstIndex (: person1))。
在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上的许多搜索方法。
你可以用闭包来过滤数组:
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
斯威夫特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)
对于自定义类,您需要实现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)