1.1类型检查:is
var movieCount = 0
var songCount = 0
for item in library {
if item in library {
movieCount += 1
}else if item is Song {
songCount += 1
}
}
1.2向下转型
用类型转换符:as?或as!
as? 返回一个可选值
as!强制形式。
for item in library {
if let movie = item as? Movie {
print("Movie: '\(movie.name)', dir. \(movie.director)")
}else if let song = item as? Song {
print("Song: '\(song.name)', by \(song.artist)")
}
1.3 Any和AnyObject的类型转换
Any:表示任何类型,包括函数类型
AnyObject:表示任何类类型
使用场景:
只有当你确实需要他们的行为和功能时才使用Any和AnyObject
var things = [Any]()
things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))
things.append({ (name: String) -> String in "Hello, \(name)" })