Swift - 类型转换
Swift 中的类型转换是什么?
类型转换是 Swift 中的一项特殊特性,用于检查实例的类型,或将来自 class、structure 或 enumeration 的实例类型更改为另一个 class、structure 或 enumeration。它很重要,因为它允许运行时类型检查和安全地将实例向下转换为子类类型。
Swift 支持两个操作符:is 和 as。is 操作符用于检查值的类型,而 as 用于将类型值转换为不同的类型。类型转换还会检查实例类型是否遵循特定的 protocol conformance 标准。
Swift 支持两种类型的类型转换 −
- Upcasting
- Downcasting
Swift 中的 Upcasting
将子类实例转换为其基类类型的过程称为 upcasting。或者可以说,upcasting 是将派生类实例视为其基类实例的过程。通过 upcasting,我们只能调用 superclass 的方法和属性。进行 upcasting 后,我们不允许直接调用子类的方法或属性,如果尝试这样做,将会得到错误。
在 Swift 中,upcasting 是隐式的,这意味着我们不需要任何特殊语法即可进行 upcasting,可以直接将子类实例转换为 superclass 实例。直接使用它是安全的,因为子类实例始终被视为 superclass 实例。Upcasting 通常在处理 polymorphic code 或希望将不同类型的实例视为其共同基类实例时使用。
示例
Swift 程序,将子类实例向上转换为 superclass 实例。
// 基类
class Shape {
func display(){
print("Ball is in the shape of sphere")
}
}
// 子类
class Rectangle: Shape {
func show(){
print("Rectangle is the most commonly used shape")
}
}
// 创建 Rectangle 类的实例
let rect = Rectangle()
// 将 rectangle 类实例向上转换为 Shape 类实例
let obj : Shape = rect
// 访问 superclass 的方法
obj.display()
// 现在我们无法直接访问子类的方法或属性
// 如果这样做,将会得到错误
// obj.show()
输出
它将产生以下输出 −
Ball is in the shape of sphere
Swift 中的向下转型
将一个 superclass type 的实例转换为 subclass type 的过程称为 downcasting。或者我们可以说是将 base class 的实例视为 derived class 的实例的过程。向下转型并不总是成功的,也可能失败。Swift 支持两种类型的 downcasting −
- 条件向下转型(as?)
- 强制向下转型(as!)
让我们详细讨论一下这两种方式
条件向下转型(as?)
条件向下转型 (as?) 操作符用于将 superclass type 的实例向下转型为特定的 subclass type。当向下转型成功时,此操作符将返回包含 subclass 实例的 optional。当向下转型失败时,此操作符将返回 nil。此操作符通常在我们不确定向下转型是否成功时使用。
语法
以下是条件向下转型操作符 (as?) 的语法 −
if let constName = instance as? Type {
// 当向下转型成功时执行的语句
} else {
// 当向下转型失败时执行的语句
}
示例
Swift 程序演示条件向下转型操作符 (as?) 的使用。
// Base Class
class ProgrammingLanguage {
func show() {
print("Welcome to the great world of learning")
}
}
// Subclass
class Swift: ProgrammingLanguage {
func display() {
print("Welcome to Swift tutorial")
}
}
let obj: ProgrammingLanguage = Swift()
// 这里条件向下转型将成功
if let result1 = obj as? Swift {
print("Downcast is successful!")
// 访问 subclass 方法
result1.display()
} else {
print("Downcast is unsuccessful")
}
// 这里条件向下转型将失败
let newObj: ProgrammingLanguage = ProgrammingLanguage()
if let result2 = newObj as? Swift {
print("\nDowncast is successful!")
result2.display()
} else {
print("Downcast is unsuccessful")
}
输出
它将产生以下输出 −
Downcast is successful! Welcome to Swift tutorial Downcast is unsuccessful
强制向下转型(as!)
强制向下转型 (as!) 操作符用于强制将实例向下转型为给定的 subclass type。此操作符将返回 subclass 的实例。如果向下转型失败,则会引发运行时错误。此操作符通常在我们确定向下转型将成功时使用。
语法
以下是强制向下转型 (as!) 的语法 −
let constantName = instance as! type
示例
Swift 程序演示强制向下转型操作符 (as!) 的使用。
// Base Class
class ProgrammingLanguage {
func show() {
print("Welcome to the great world of learning")
}
}
// Subclass
class Swift: ProgrammingLanguage {
func display() {
print("Welcome to Swift tutorial")
}
}
let obj: ProgrammingLanguage = Swift()
// 这里强制向下转型将成功
let res1 = obj as! Swift
// 访问 Swift class 的方法
res1.display()
// 这里强制向下转型将失败,因此我们会得到一个错误
/*let newobj: ProgrammingLanguage = ProgrammingLanguage()
let res2 = newobj as! Swift
res2.display()*/
输出
它将产生以下输出 −
Welcome to Swift tutorial
类型检查
在 Swift 中,type-checking 用于确定给定的实例是否属于指定的子类。我们可以使用 is 操作符进行 type-checking。如果实例属于指定的 class,则该操作符将返回 true。如果实例不属于指定的 class,则该操作符将返回 false。
语法
以下是 type checking 的语法 −
let constantName = instance as! type
示例
Swift 程序演示如何检查实例的类型。
// 基类
class ProgrammingLanguage {
func show() {
print("Welcome to the great world of learning")
}
}
// 子类
class Swift: ProgrammingLanguage {
func display() {
print("Welcome to Swift tutorial")
}
}
let obj: ProgrammingLanguage = Swift()
// 类型检查
if obj is Swift{
print("obj is the instance of Swift class")
} else {
print("No obj is not the instance of Swift class")
}
输出
它将产生以下输出 −
obj is the instance of Swift class
Any 和 AnyObject 的类型转换
Swift 支持两种特殊类型,用于处理未知类型的 value 和 class 的 instance,这些类型是:
Any −
Any用于表示属于任何类型(包括 function types)的 instance。它还包括 optional types。AnyObject −
AnyObject用于表示任何 class type 的 instance。
我们可以在 Any 和 AnyObject 上执行 type casting 和 type checking。
示例
Swift 程序演示 Any 的 type casting。
// Any 的类型转换
var myValue: Any = 22
// 使用 is 操作符进行类型检查
if myValue is Int {
print("Yes myValue is of Int type!")
} else {
print("No myValue is not of Int type!")
}
// 使用 as? 操作符进行类型转换
if let res = myValue as? Int {
print("Successfully casted to Int: \(res)")
} else {
print("Could not be able to cast into Int")
}
输出
它将产生以下输出 −
Yes myValue is of Int type! Successfully casted to Int: 22
示例
Swift 程序演示 AnyObject 的 type casting。
// 基类
class ProgrammingLanguage {
func show() {
print("Welcome to the great world of learning")
}
}
// 子类
class Swift: ProgrammingLanguage {
func display() {
print("Welcome to Swift tutorial")
}
}
// 任意对象类型的实例
let obj: AnyObject = Swift()
// 使用 is 操作符进行类型检查
if obj is Swift {
print("Yes it is the instance of Swift")
} else {
print("No it is not the instance of Swift")
}
// 使用 as? 操作符进行类型转换
if let res = obj as? Swift {
print("Successfully casted to Swift")
res.display()
} else {
print("Could not cast to Swift")
}
输出
它将产生以下输出 −
Yes it is the instance of Swift Successfully casted to Swift Welcome to Swift tutorial