Swift 4类型转换介绍和用法示例

本文概述

  • 定义类层次结构
  • 如何进行类型检查
Swift4中使用Typecasting来验证实例的类型。它用于检查实例类型是属于特定的超类还是子类, 或者是否在其自己的层次结构中定义。
Swift 4类型转换提供两个运算符:
  • ‘ is’ :此运算符用于检查值的类型。
  • ‘ as’ :此运算符用于将类型值转换为其他类型。
定义类层次结构类型转换还用于检查实例类型是否遵循特定的协议一致性标准。它还检查类的层次结构, 其子类及其实例, 以使其成为同一层次结构。
例:
class Subjects {var physics: Stringinit(physics: String) {self.physics = physics}}class Chemistry: Subjects {var equations: Stringinit(physics: String, equations: String) {self.equations = equationssuper.init(physics: physics)}}class Maths: Subjects {var formulae: Stringinit(physics: String, formulae: String) {self.formulae = formulaesuper.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: MechanicsInstance equation is: HertzInstance physics is: Fluid DynamicsInstance formulae is: Giga Hertz

如何进行类型检查【Swift 4类型转换介绍和用法示例】” is” 运算符用于进行类型检查。它检查实例是否属于特定的子类类型, 如果实例属于, 则返回” true” , 否则返回” false” 。

    推荐阅读