簡體   English   中英

AnyObject數組的indexOf不能與字符串一起使用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM