點擊查看源碼
//類型選擇
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)" }) // 閉包
}