swift中的类型转换使用is
和 as
操作符。
Checking Type
使用is
操作符判断一个实例是否是特定字类。
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
Downcasting
某个类型的常量和变量可能属于某种特定类型。可以使用as!
或 as?
操作符向下转型为特定字类。
向下转型可能会失败,所以类型转换操作符有两种形式,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)")
}
}
Type Casting for Any and AnyObject
swift提供了两种特殊的类型:
- 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)" })
判断Any 或 AnyObject 类型变量的确切类型可以在switch中使用as
或 is
匹配模式。
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 (x, y) as (Double, Double):
print("an (x, y) point at \(x), \(y)")
case let movie as Movie:
print("a movie called \(movie.name), dir. \(movie.director)")
case let stringConverter as (String) -> String:
print(stringConverter("Michael"))
default:
print("something else")
}
}
Any 也可以表示可选类型,把一个可选类型加入数据会产生警告。可以使用as
操作符把它明确转成Any类型。
let optionalNumber: Int? = 3
things.append(optionalNumber) // Warning
things.append(optionalNumber as Any) // No warning