點擊查看源碼git
//類型選擇 func test() { class MediaItem { } class Movie: MediaItem { } class Song: MediaItem { } let array = [Song(), Movie()] //is測試 類型判斷 for item in array { if item is Movie { print("Movie構建") } else if item is Song { print("Song構建") } } //as測試 類型轉換 for item in array { if let movie = item as? Movie { print("可轉換爲Movie: '\(movie)'") } else if let song = item as? Song { print("可轉換爲Song: '\(song)'") } } //AnyObject能夠是任何類型的一個實例 值類型或引用類型 let someObjects: [AnyObject] = [Movie(), 1 as AnyObject, "33" as AnyObject] print(someObjects) //Any任何類型數據 還能夠是函數 閉包等 var things = [Any]() things.append(0) //值類型 things.append(Movie()) //引用類型 things.append({ (name: String) -> String in "Hello, \(name)" }) // 閉包 }