获取数组中项目索引的最有效方法是什么?在Objective-C中,我们曾经能够做到:
[arrayName indexOfObject:myObject]
在Swift中,我知道我们可以做到以下几点。
index =arrayName.indexOf({$0 === myObject})
这是最干净,最有效的方法吗?
答案 0 :(得分:11)
As Oliver pointed out, you can use
let index = array.indexOf(myObject)
However, this will only work if your object conforms to the Equatable
protocol, to conform to it, you have to implement the ==
function, like this:
class MyClass {
}
extension MyClass: Equatable { }
func ==(lhs: MyClass, rhs: MyClass) -> Bool {
return lhs === rhs // === returns true when both references point to the same object
}
If your class inherits from NSObject
and your comparison is something other than just comparing pointers, you'll have to override isEqual:
as well
override func isEqual(object: AnyObject?) -> Bool {
guard let obj = object as? MyClass else { return false }
return self == obj
}
答案 1 :(得分:3)
You can use:
let index = array.indexOf(myObject)
You don't need to use the closure as indexOf accepts the element itself as an argument
Bear in mind that index is optional though