1. 强制类型转换
强制类型转换用于把一个类型当做另一种类型处理,但是需要确保实例确实属于被转换的类型,否则会在运行时触发运行时错误。
从子类到父类的强制转换
class Animal {
var name: String
init(name: String) {
self.name = name
}
}
class Dog: Animal {
var breed: String
init(name: String, breed: String) {
self.breed = breed
super.init(name: name)
}
}
let myDog = Dog(name: "Buddy", breed: "Golden Retriever")
let animal: Animal = myDog
// 从子类到父类的强制转换
let castedDog = animal as! Dog
print(castedDog.name) // 输出 "Buddy"
print(castedDog.breed) // 输出 "Golden Retriever"
从父类到子类的强制转换
class Shape {
func draw() {
print("Drawing a shape")
}
}
class Circle: Shape {
var radius: Double
init(radius: Double) {
self.radius = radius
super.init()
}
override func draw() {
print("Drawing a circle with radius \(radius)")
}
}
let shape: Shape = Circle(radius: 5.0)
// 从父类到子类的强制转换
let castedCircle = shape as! Circle
castedCircle.draw() // 输出 "Drawing a circle with radius 5.0"
2. 条件类型转换
条件类型转换用于检查实例是否属于特定类型。它使用 is 关键字,返回一个布尔值。
检查类型
class Movie {
var title: String
init(title: String) {
self.title = title
}
}
class Song {
var title: String
init(title: String) {
self.title = title
}
}
let mediaItems: [Any] = [Movie(title: "Inception"), Song(title: "Shape of You")]
for item in mediaItems {
// 检查类型
if item is Movie {
print("It's a Movie")
} else if item is Song {
print("It's a Song")
}
}
向下类型转换
向下类型转换用于将基类类型的实例转换为子类类型。它使用 as? 或 as! 关键字。
- 使用 as? 时,如果转换失败,返回 nil。
- 使用 as! 时,如果转换失败,会触发运行时错误。
for item in mediaItems {
// 向下类型转换
if let movie = item as? Movie {
print("Movie: \(movie.title)")
} else if let song = item as? Song {
print("Song: \(song.title)")
}
}
以上是一些关于 Swift 类型转换的基本用法。类型转换允许你在 Swift 中处理不同类型的实例,但需要谨慎使用,以确保转换的安全性。
转载请注明出处:http://www.zyzy.cn/article/detail/14437/Swift