類(lèi)型推斷
import UIKit
class MediaItem {
var name: String
init(name: String) {
self.name = name
}
}
class Movie: MediaItem {
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
}
}
class Song: MediaItem {
var artist: String
init(name: String, artist: String) {
self.artist = artist
super.init(name: name)
}
}
let library = [
Movie(name: "北京愛(ài)情故事", director: "陳思誠(chéng)"),
Song(name: "終于等到你", artist: "張靚穎"),
Movie(name: "北京遇上西雅圖", director: "薛曉路"),
Song(name: "一次就好", artist: "王凱"),
Song(name: "匆匆那年", artist: "王菲")
]
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
print("Media library contains \(movieCount) movies and \(songCount) songs")
for item in library {
if let movie = item as? Movie {
print("電影: \(movie.name), 導(dǎo)演 \(movie.director)")
} else if let song = item as? Song {
print("歌曲: \(song.name), 演唱者 \(song.artist)")
}
}
let someObjects: [AnyObject] = [
Movie(name: "北京愛(ài)情故事", director: "陳思誠(chéng)"),
Movie(name: "北京遇上西雅圖", director: "薛曉路"),
Movie(name: "失戀三十三天", director: "滕華濤")
]
for object in someObjects {
let movie = object as! Movie
print("電影: \(movie.name), 導(dǎo)演 \(movie.director)")
}
for movie in someObjects as! [Movie] {
print("電影: \(movie.name), 導(dǎo)演 \(movie.director)")
}
var things = [Any]()
things.append(0)
things.append(0.0)
things.append(520)
things.append(3.14159)
things.append("hello")
things.append(Movie(name: "失戀三十三天", director: "滕華濤"))
things.append({
(name: String) -> String in "I Love U, \(name)"
})
things.append(-1992.85)
for thing in things {
switch thing {
case 0 as Int:
print("zero as an Int")
case 0 as Double:
print("zero as a Double")
case let someInt as Int:
print("an integer value of \(someInt)")
case let someDouble as Double where someDouble > 0:
print("a positive double value of \(someDouble)")
case is Double:
print("some other double value that i don't want to print")
case let someString as String:
print("a string value of \(someString)")
case let movie as Movie:
print("電影: \(movie.name), 導(dǎo)演 \(movie.director)")
case let stringConverter as (String) -> String:
print(stringConverter("XiaoYao"))
default:
print("something else")
}
}
console log 如下