2015-10-05 72 views
4

所以我有一個playgroung下面的代碼AnyObject陣列的indexOf不處理字符串

var array: [AnyObject] = ["", "2", "3"] 

let index = array.indexOf("") 

而且Xcode是標誌着一個編譯器錯誤

Cannot convert value of type 'String' to expected argument type '@noescape (AnyObject) throws -> Bool'

所以我的問題是如何在AnyObject中的數組中獲取indexOf元素嗎?

+0

你爲什麼不使用'[字符串]',你應該很少使用'AnyObject',特別是在迅速!你應該總是指定你的數組持有什麼! – AaoIi

+0

'AnyObject'是「未指定」的佔位符。該數組顯然是一個字符串數組,所以只需刪除註釋'[AnyObject]'。編譯器會推斷正確的事情。 – vadian

+0

如果數組是一個在目標C類中定義的NSArray,該怎麼辦? –

回答

5

您也可以轉換爲[字符串]如果你相信它會投安全

jvar array: [AnyObject] = ["", "2", "3"] 
let index = (array as! [String]).indexOf("") 
+0

這是我在尋找的感謝! –

+0

不客氣:) – Lukas

3

試試這個

var array = ["", "2", "3"] 
let index = array.indexOf("") 

,或者您可以使用NSArray方法:

var array: [AnyObject] = ["", "2", "3"] 
let index = (array as NSArray).indexOfObject("") 
0

你不應該使用AnyObject一個佔位符的任何類型,使用Any代替。原因:AnyObject僅適用於類,Swift雖然使用了很多結構(數組,字符串,字符串等)。您的代碼實際上使用NSString s而不是Swifts本地String類型,因爲AnyObject需要一個類(NSString是一個類)。

+0

我同意你我只是用一種簡單的方法來說明當我在某個目標C類中定義了一個'NSArray'並且在一個快速類中被訪問時我的問題。 –

0

在更一般的情況下,當一個數組裏面的對象都符合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