Swift 中的类型转换是什么?如何使用 is、as、as? 和 as! 进行类型转换?
Swift 中的类型转换用于检查实例的类型,或者将其视为超类或子类。类型转换在处理多态和继承层次结构时非常重要。
is 操作符:
- 检查实例是否是特定类型的实例
- 返回布尔值
- 示例:
swift
class Vehicle {} class Car: Vehicle {} class Truck: Vehicle {} let vehicle = Car() print(vehicle is Car) // true print(vehicle is Vehicle) // true print(vehicle is Truck) // false
as 操作符:
- 用于向上转换(子类到父类)
- 总是成功
- 示例:
swift
let car = Car() let vehicle = car as Vehicle
as? 操作符:
- 用于向下转换(父类到子类)
- 返回可选类型
- 转换失败时返回 nil
- 示例:
swift
let vehicle: Vehicle = Car() if let car = vehicle as? Car { print("This is a car") } if let truck = vehicle as? Truck { print("This is a truck") } else { print("Not a truck") }
as! 操作符:
- 用于强制向下转换
- 转换失败时触发运行时错误
- 只在确定转换会成功时使用
- 示例:
swift
let vehicle: Vehicle = Car() let car = vehicle as! Car // 危险:可能导致崩溃 // let truck = vehicle as! Truck
类型转换的实际应用:
swiftclass 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: "Casablanca", director: "Michael Curtiz"), Song(name: "Blue Suede Shoes", artist: "Elvis Presley"), Movie(name: "Citizen Kane", director: "Orson Welles"), Song(name: "The One And Only", artist: "Chesney Hawkes"), Song(name: "Never Gonna Give You Up", artist: "Rick Astley") ] 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: \(movie.name), dir. \(movie.director)") } else if let song = item as? Song { print("Song: \(song.name), by \(song.artist)") } }
Any 和 AnyObject 类型转换:
swiftvar 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")) 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)") default: print("something else") } }
最佳实践:
- 使用 is 检查类型
- 使用 as? 安全地进行类型转换
- 只在确定转换会成功时使用 as!
- 使用 switch 处理多种类型
- 避免过度使用 Any 和 AnyObject