📜  Swift类型转换

📅  最后修改于: 2021-01-11 08:01:50             🧑  作者: Mango

Swift4类型转换

在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”。