[英]indexOf of AnyObject array not working with Strings
所以我在playgroung中有以下代碼
var array: [AnyObject] = ["", "2", "3"]
let index = array.indexOf("")
並且XCode標記了編譯器錯誤
Cannot convert value of type 'String' to expected argument type '@noescape (AnyObject) throws -> Bool'
所以我的問題是如何在AnyObjects的Array中獲取indexOf元素?
如果你確定它會安全地轉換,你也可以轉換為[String]
jvar array: [AnyObject] = ["", "2", "3"]
let index = (array as! [String]).indexOf("")
嘗試這個
var array = ["", "2", "3"]
let index = array.indexOf("")
或者你可以使用NSArray
方法:
var array: [AnyObject] = ["", "2", "3"]
let index = (array as NSArray).indexOfObject("")
永遠不要將AnyObject
用於任何類型的占位符,而是使用Any
。 原因: AnyObject
只適用於類,Swift雖然使用了很多結構(Array,Int,String等)。 您的代碼實際上使用NSString
而不是Swifts本機String
類型,因為AnyObject
一個類( NSString
是一個類)。
在更一般的情況下,當數組內的對象符合Equatable
協議時, collectionType.indexOf
將起作用。 由於Swift String
已經符合Equatable
,因此將AnyObject
轉換為String
將刪除錯誤。
如何在集合類型自定義類上使用indexOf
? 斯威夫特2.3
class Student{
let studentId: Int
let name: String
init(studentId: Int, name: String){
self.studentId = studentId
self.name = name
}
}
//notice you should implement this on a global scope
extension Student: Equatable{
}
func ==(lhs: Student, rhs: Student) -> Bool {
return lhs.studentId == rhs.studentId //the indexOf will compare the elements based on this
}
func !=(lhs: Student, rhs: Student) -> Bool {
return !(lhs == rhs)
}
現在你可以像這樣使用它
let john = Student(1, "John")
let kate = Student(2, "Kate")
let students: [Student] = [john, kate]
print(students.indexOf(John)) //0
print(students.indexOf(Kate)) //1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.