类型转换 #
一、类型转换概述 #
Swift中的类型转换包括:
- 类型检查:使用
is检查类型 - 类型转换:使用
as转换类型 - 类型判断:使用
type(of:)获取类型
二、类型检查(is) #
2.1 基本用法 #
swift
let value: Any = "Hello"
if value is String {
print("是字符串")
}
if value is Int {
print("是整数")
}
2.2 检查类类型 #
swift
class Animal {}
class Dog: Animal {}
class Cat: Animal {}
let dog = Dog()
let cat = Cat()
let animals: [Animal] = [dog, cat]
for animal in animals {
if animal is Dog {
print("这是一只狗")
} else if animal is Cat {
print("这是一只猫")
}
}
2.3 检查协议遵循 #
swift
protocol Drawable {
func draw()
}
class Circle: Drawable {
func draw() {
print("画圆")
}
}
class Square {
func draw() {
print("画方")
}
}
let shapes: [Any] = [Circle(), Square()]
for shape in shapes {
if shape is Drawable {
print("可以绘制")
}
}
三、类型转换(as) #
3.1 向上转型(as) #
swift
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 dog = Dog(name: "旺财", breed: "金毛")
let animal = dog as Animal
print(animal.name)
3.2 向下转型(as?) #
swift
let animals: [Animal] = [
Dog(name: "旺财", breed: "金毛"),
Animal(name: "动物")
]
for animal in animals {
if let dog = animal as? Dog {
print("狗: \(dog.name), 品种: \(dog.breed)")
} else {
print("普通动物: \(animal.name)")
}
}
3.3 强制转换(as!) #
swift
let animal: Animal = Dog(name: "旺财", breed: "金毛")
let dog = animal as! Dog
print(dog.breed)
let anotherAnimal = Animal(name: "动物")
let anotherDog = anotherAnimal as! Dog
3.4 桥接转换 #
swift
let swiftString = "Hello"
let nsString = swiftString as NSString
let swiftArray = [1, 2, 3]
let nsArray = swiftArray as NSArray
四、Any和AnyObject #
4.1 Any类型 #
Any 可以表示任何类型的实例:
swift
var anyValue: Any = 42
anyValue = "Hello"
anyValue = [1, 2, 3]
anyValue = { print("闭包") }
4.2 AnyObject类型 #
AnyObject 可以表示任何类类型的实例:
swift
class Person {
var name: String
init(name: String) {
self.name = name
}
}
var anyObject: AnyObject = Person(name: "张三")
anyObject = UIView()
4.3 使用场景 #
swift
let mixedArray: [Any] = [
42,
"Hello",
3.14,
[1, 2, 3],
Person(name: "张三")
]
for item in mixedArray {
switch item {
case let intValue as Int:
print("整数: \(intValue)")
case let stringValue as String:
print("字符串: \(stringValue)")
case let doubleValue as Double:
print("浮点数: \(doubleValue)")
case let array as [Int]:
print("数组: \(array)")
case let person as Person:
print("人: \(person.name)")
default:
print("未知类型")
}
}
五、类型转换模式 #
5.1 switch中的类型匹配 #
swift
let value: Any = 42
switch value {
case is Int:
print("是整数")
case is String:
print("是字符串")
case is Double:
print("是浮点数")
default:
print("未知类型")
}
5.2 绑定模式 #
swift
let value: Any = "Hello"
switch value {
case let intValue as Int:
print("整数: \(intValue)")
case let stringValue as String:
print("字符串: \(stringValue)")
case let doubleValue as Double:
print("浮点数: \(doubleValue)")
default:
print("未知类型")
}
5.3 可选模式 #
swift
let optionalValue: Any = Optional(42)
switch optionalValue {
case let wrapped?:
print("有值: \(wrapped)")
case nil:
print("无值")
}
六、类型别名 #
6.1 基本用法 #
swift
typealias Age = Int
typealias Name = String
typealias Coordinate = (x: Double, y: Double)
var age: Age = 25
var name: Name = "张三"
var point: Coordinate = (x: 10.0, y: 20.0)
6.2 闭包类型别名 #
swift
typealias Completion = () -> Void
typealias Result<T> = (T?, Error?) -> Void
typealias Transform<T, U> = (T) -> U
var callback: Completion = {
print("完成")
}
var handler: Result<String> = { result, error in
if let result = result {
print(result)
}
}
6.3 协议类型别名 #
swift
typealias DataSource = UITableViewDataSource & UICollectionViewDataSource
typealias Delegate = UITableViewDelegate & UICollectionViewDelegate
class ViewController: UIViewController {
var dataSource: DataSource?
var delegate: Delegate?
}
七、实际应用 #
7.1 JSON解析 #
swift
let json: [String: Any] = [
"name": "张三",
"age": 25,
"scores": [90, 85, 88]
]
if let name = json["name"] as? String,
let age = json["age"] as? Int,
let scores = json["scores"] as? [Int] {
print("姓名: \(name)")
print("年龄: \(age)")
print("成绩: \(scores)")
}
7.2 视图控制器转换 #
swift
func handleViewController(_ vc: UIViewController) {
if let navVC = vc as? UINavigationController {
print("导航控制器")
} else if let tabVC = vc as? UITabBarController {
print("标签控制器")
} else {
print("普通控制器")
}
}
7.3 集合类型转换 #
swift
let numbers = [1, 2, 3, 4, 5]
let anyArray: [Any] = numbers.map { $0 as Any }
let strings = ["1", "2", "3"]
let ints = strings.compactMap { Int($0) }
print(ints)
八、类型推断 #
8.1 字面量推断 #
swift
let integer = 42
let double = 3.14
let string = "Hello"
let array = [1, 2, 3]
let dictionary = ["key": "value"]
print(type(of: integer))
print(type(of: double))
print(type(of: string))
8.2 上下文推断 #
swift
let numbers: [Double] = [1, 2, 3]
let doubled = numbers.map { $0 * 2 }
print(type(of: doubled))
func acceptString(_ value: String) { }
acceptString("Hello")
8.3 显式类型 #
swift
let explicitInt: Int = 42
let explicitDouble: Double = 3
let explicitArray: [String] = ["a", "b", "c"]
九、类型安全 #
9.1 编译时检查 #
swift
var name: String = "Swift"
name = 42
var age: Int = 25
age = "25"
9.2 类型不匹配 #
swift
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
let result = add(1, 2.0)
9.3 可选类型安全 #
swift
var name: String? = "Swift"
let length = name.count
let safeLength = name?.count ?? 0
十、总结 #
本章学习了Swift的类型转换:
- 类型检查:使用
is检查类型 - 类型转换:使用
as、as?、as!转换类型 - Any和AnyObject:表示任意类型
- 类型别名:为类型创建别名
最佳实践:
- 优先使用
as?而非as! - 尽量避免使用
Any和AnyObject - 使用类型别名提高代码可读性
- 利用类型推断简化代码
下一章,我们将学习Swift的运算符!
最后更新:2026-03-26