Swift 类型转换
类型转换在Swift4中用于验证实例的类型。它用于检查实例类型是否属于特定的父类或子类,或者它是否在自己的层次结构中定义。
Swift 4类型转换提供两个操作符:
- ‘is’ :该运算符用于检查值的类型。
- ‘as’ :该运算符用于将类型值转换为不同的类型。
定义类的层次结构
类型转换还用于检查实例类型是否符合特定的协议一致性标准。它还检查类的层次结构、其子类和实例,使其成为相同的层次结构。
示例
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}
class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}
class Maths: Subjects {
var formulae: String
init(physics: String, formulae: String) {
self.formulae = formulae
super.init(physics: physics)
}
}
let sa = [ Chemistry(physics: "Mechanics", equations: "Hertz"),
Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")]
let samplechem = Chemistry(physics: "Mechanics", equations: "Hertz")
print("Instance physics is: \(samplechem.physics)")
print("Instance equation is: \(samplechem.equations)")
let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
print("Instance physics is: \(samplemaths.physics)")
print("Instance formulae is: \(samplemaths.formulae)")
输出:
Instance physics is: Mechanics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
如何进行类型检查
“is”运算符用于进行类型检查。它检查实例是否属于特定的子类类型,并在属于时返回“true”,否则返回“false”。