Swift 类型检查与类型转换

前言

  • 在 Swift 语言中一般使用 is 关键字实现类型检查,使用 as 关键字实现类型转换,除此之外还可以通过构造器和方法来实现类型转换。

1、类型检查

1.1 使用 is 检查

  • 类型检查操作符 is 可以用来检查一个实例是否属于特定子类型,若属于那个类型,则类型检查操作符返回 true, 否则返回 false

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    class Transport {

    var scope = ""

    init(scope: String) {
    self.scope = scope
    }
    }

    class Car: Transport {

    var type = "daba"

    init(scope: String, type: String) {
    super.init(scope: scope)
    self.type = type
    }
    }

    class Airplance: Transport {

    var company = "dongfanghangkong"

    init(scope: String, company: String) {
    super.init(scope: scope)
    self.company = company
    }
    }

    var carNum = 0
    var airNum = 0

    let journey = [
    Car(scope: "ludi", type: "daba"),
    Car(scope: "ludi", type: "gongjiaoche"),
    Airplance(scope: "hangkong", company: "dongfanghangkong"),
    Car(scope: "ludi", type: "chuzuche")
    ]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    for tra in journey {

    if tra is Car { // 检查是否属于 Car 类型
    carNum += 1
    } else if tra is Airplance { // 检查是否属于 Airplance 类型
    airNum += 1
    }
    }

    print(carNum) // 3
    print(airNum) // 1

1.2 使用 as? 检查

  • 安全转型 as?,用于不确定是否可以转型成功的情况,如果转型成功则执行转型,如果转型行不通,就会返回 nil,这时可以使用 as? 做类型检查。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    for tra in journey {

    if let _ = tra as? Car { // 检查是否属于 Car 类型
    carNum += 1
    } else if let _ = tra as? Airplance { // 检查是否属于 Airplance 类型
    airNum += 1
    }
    }

    print(carNum) // 3
    print(airNum) // 1

2、类型转换

2.1 使用 as 转换

  • 有时候我们需要的某个类型的实例可能实际上是该类型的一个子类,可以使用关键字 as 尝试对它使用向下转型得到它的子类。

  • 向下转型分为两种。

    • 安全转型 as?,用于不确定是否可以转型成功的情况,如果转型成功则执行转型,如果转型行不通,就会返回 nil,这时可以使用 as? 做类型检查。
    • 强制转型 as!,只用在确定向下转型一定能够成功的情况下,当试图将实例向下转为一个不正确的类型时,会抛出异常。
  • is 关键字相比,使用 as 除了可以检查类型外,还可以访问子类的属性或者方法。通常为了使用转型成功的实例,搭配使用可选绑定。

    1
    2
    3
    4
    5
    6
    7
    8
    for tra in journey {

    if let car = tra as? Car { // 转换成 Car 类型
    print(car.type)
    } else if let airplane = tra as? Airplance { // 转换成 Airplance 类型
    print(airplane.company)
    }
    }

2.2 使用 “构造器的方法” 转换

  • 使用类型的构造器转换

    1
    2
    let d: Double = 12.3
    let i = Int(d) // 12
文章目录
  1. 1. 前言
  2. 2. 1、类型检查
    1. 2.1. 1.1 使用 is 检查
    2. 2.2. 1.2 使用 as? 检查
  3. 3. 2、类型转换
    1. 3.1. 2.1 使用 as 转换
    2. 3.2. 2.2 使用 “构造器的方法” 转换
隐藏目录