Swift 类型转换
Swift 语言类型转换可以判断实例的类型。也可以用于检测实例类型是否属于其父类或者子类的实例。
Swift 中类型转换使用 is 和 as 操作符实现,is 用于检测值的类型,as 用于转换类型。
类型转换也可以用来检查一个类是否实现了某个协议。
检查类型
类型转换用于检测实例类型是否属于特定的实例类型。
你可以将它用在类和子类的层次结构上,检查特定类实例的类型并且转换这个类实例的类型成为这个层次结构中的其他类型。
类型检查使用 is 关键字。
操作符 is 来检查一个实例是否属于特定子类型。若实例属于那个子类型,类型检查操作符返回 true,否则返回 false。
//超类携带公共属性name
class Subject {
var name: String
init(name: String) {
self.name = name
}
}
class ManKind: Subject {
var gender: String
init(gender: String, name: String) {
self.gender = gender
super.init(name: name)
}
}
class Creature: Subject {
var fauna: String
init(fauna: String, name: String) {
self.fauna = fauna
super.init(name: name)
}
}
let array = [ManKind(gender: "Female", name: "lily"),
ManKind(gender: "Male", name: "Jack"),
Creature(fauna: "Dog", name: "haha"),
Creature(fauna: "Fish", name: "jinjin"),
Creature(fauna: "Tree", name: "apple")]
var manKindCount = 0
var creatureCount = 0
for item in array {
//类型检查使用 is 关键字
if item is ManKind {
manKindCount += 1}
else if item is Creature {
creatureCount += 1}
}
print("数组中共有\(manKindCount)个人类,\(creatureCount)个动植物")
运行结果:
数组中共有2个人类,3个动植物
向下转型
向下转型,用类型转换操作符(as? 或 as!)
当你不确定向下转型可以成功时,用类型转换的条件形式(as?)。条件形式的类型转换总是返回一个可选值(optional value),并且若下转是不可能的,可选值将是 nil。
只有你可以确定向下转型一定会成功时,才使用强制形式(as!)。当你试图向下转型为一个不正确的类型时,强制形式的类型转换会触发一个运行时错误
for item in array {
if let people = item as? ManKind {
print("\(people.name) is \(people.gender)")
}else if let creature = item as? Creature {
print("\(creature.name) is \(creature.fauna)")
}
}
运行结果:
lily is Female
haha is Dog
Jack is Male
jinjin is Fish
apple is Tree
Any和AnyObject的类型转换
Swift为不确定类型提供了两种特殊类型别名:
- AnyObject可以代表任何class类型的实例。
- Any可以表示任何类型,包括方法类型(function types)。
注意:
只有当你明确的需要它的行为和功能时才使用Any和AnyObject。在你的代码里使用你期望的明确的类型总是更好的。
AnyObject 实例
//数组存放class类型实例,不能存int double string等类型
let array: [AnyObject] = [ManKind(gender: "Female", name: "lily"),
ManKind(gender: "Male", name: "Jack"),
Creature(fauna: "Dog", name: "haha"),
Creature(fauna: "Fish", name: "jinjin"),
Creature(fauna: "Tree", name: "apple")]
Any 实例
//Any可以表示任何类型,包括方法类型(function types)。
var arrayM = [Any]()
arrayM.append(80)
arrayM.append(3.1415)
arrayM.append("字符串")
arrayM.append(ManKind(gender: "Male", name: "Jason"))
arrayM.append(Creature(fauna: "Pest", name: "蚊子"))
for item in arrayM {
switch item {
case let people as ManKind:
print("\(people.name) is \(people.gender)")
case let creature as Creature:
print("\(creature.name) is \(creature.fauna)")
case let number as Int:
print(number)
case let