美文网首页
as as! as?的使用方法和区别

as as! as?的使用方法和区别

作者: Qing学 | 来源:发表于2017-10-24 10:51 被阅读0次

    as、as!、as?都是类型转换操作符

    一、as

    1.用来进行一般的向上类型转换

    例如

    
    class Person{}
    
    class XiaoMing : Person{}
    
    let xiaoMing = XiaoMing()
    
    let person = xiaoMing as Person
    
    

    在这个类里面就将子类对象xiaoMing转化为了父类Person对象并赋值给了person

    2.进行数值类型限定转换,也是起到了一个说明的作用

    
    let num1 =25 as CGFloat
    
    let num2 =3 as Int
    
    let num3 = (1 / 3) as CGFloat
    
    let num4 =1.45 as Int
    
    

    3.用在switch条件判断语句中

    
    class Person{}
    
    class XiaoMing : Person{}
    
    class XiaoGang : Person{}
    
    let xiaoMing = XiaoMing()
    
    _ = XiaoGang()
    
    let person = xiaoMing as Person
    
    switch person {
    
    case letming as XiaoMing:
    
      print (ming)
    
    case let gang as XiaoGang:
    
      print (gang)
    
    default: break
    
    }
    
    

    二、as!

    进行强制向下的类型转换例如:(如果类型转换不成功会报runtime崩溃)

    class Person{}
    
    class XiaoMing : Person{}
    
    let person : Person = XiaoMing()
    
    let xiaoMing : XiaoMing = person as! XiaoMing
    

    三、as?

    as?如果类型转换不成功就会返回一个nil对象,不确定是否一定可以转化的时候可以使用as?

    
    class Person{}
    
    class XiaoMing : Person{}
    
    let person : Person = XiaoMing()
    
    if let xiaoMing = person as! XiaoMing{
    
        print("xiaoMing不为nil")
    
    }else{
    
        print("xiaoMing为nil")
    
    }
    
    

    总结:as用于向上转换、数字类型转换、Switch类型判断

    as!和as?用于向下类型转换。不确定成功用as?一定成功用as!

    相关文章

      网友评论

          本文标题:as as! as?的使用方法和区别

          本文链接:https://www.haomeiwen.com/subject/mkjtpxtx.html