zoukankan      html  css  js  c++  java
  • Swift

    as、as!、as? 这三种类型转换操作符的异同,以及各自的使用场景。
     
    1,as使用场合
    (1)从派生类转换为基类,向上转型(upcasts)
    1
    2
    3
    4
    class Animal {}
    class CatAnimal {}
    let cat = Cat()
    let animal = cat as Animal
     
    (2)消除二义性,数值类型转换
    1
    2
    3
    4
    let num1 = 42 as CGFloat
    let num2 = 42 as Int
    let num3 = 42.5 as Int
    let num4 = (42 / 2) as Double
     
    (3)switch 语句中进行模式匹配
    如果不知道一个对象是什么类型,你可以通过switch语法检测它的类型,并且尝试在不同的情况下使用对应的类型进行相应的处理。
    1
    2
    3
    4
    5
    6
    7
    switch animal {
    case let cat as Cat:
        print("如果是Cat类型对象,则做相应处理")
    case let dog as Dog:
        print("如果是Dog类型对象,则做相应处理")
    defaultbreak
    }
     
    2,as!使用场合
    向下转型(Downcasting)时使用。由于是强制类型转换,如果转换失败会报 runtime 运行错误。
    1
    2
    3
    4
    class Animal {}
    class CatAnimal {}
    let animal :Animal  Cat()
    let cat = animal asCat

    3,as?使用场合
    as? 和 as! 操作符的转换规则完全一样。但 as? 如果转换不成功的时候便会返回一个 nil 对象。成功的话返回可选类型值(optional),需要我们拆包使用。
    由于 as? 在转换失败的时候也不会出现错误,所以对于如果能确保100%会成功的转换则可使用 as!,否则使用 as?
    1
    2
    3
    4
    5
    6
    7
    let animal:Animal Cat()
     
    if let cat = animal asCat{
        print("cat is not nil")
    else {
        print("cat is nil")
    }
  • 相关阅读:
    leetcode刷题 650~
    leetcode刷题 633~
    发送udp报文
    SIP (Session Initiation Protocol) 协议
    你所不知道的replace
    uni-app(六)生成海报图片路径问题
    uni-app(五)小程序的一些注意事项,踩坑
    uni-app(四)小程序里的vuex
    uni-app(三)组件、插件使用,引入字体
    uni-app(二)接口请求封装,全局输出api
  • 原文地址:https://www.cnblogs.com/gongyuhonglou/p/5919908.html
Copyright © 2011-2022 走看看