Swift 类型检查与类型转换

前言

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

1、类型检查

1.1 使用 is 检查

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

    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")
    ]
    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? 做类型检查。

    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 除了可以检查类型外,还可以访问子类的属性或者方法。通常为了使用转型成功的实例,搭配使用可选绑定。

    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 使用 “构造器的方法” 转换

  • 使用类型的构造器转换

    let d: Double = 12.3
    let i = Int(d)              // 12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值