本文概述
Swift4中使用Typecasting来验证实例的类型。它用于检查实例类型是属于特定的超类还是子类, 或者是否在其自己的层次结构中定义。
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”。
评论前必须登录!
注册