Swift4.2~as,as!,as?

https://www.cnblogs.com/dukework/p/6553714.html

一,as

类型转换
as :同类型的数据 OC和Swift之间转换

let NetWorkData = Data.init()
let netData = NetWorkData as NSData
print(netData)
        
let NetWorkStr = "Network"
let NetStr = NetWorkStr as NSString
print(NetStr)

二,as!

类型的强制转换
as!操作符是类型转换的强制格式,优点在于代码简单,如果可以转换,则会返回转换了格式的对象,如果无法转换就会抛出运行时错误。因此除非百分之百确定可以转换,否则不应该使用as!来进行强制类型转换。

class NetWClass:NSObject{
       var name:String = "NetWClass强制转换成功"
}
        
 /**
类型的转换 Any -> NetWClass
*/
        
let paramClass:[Any] = [NetWClass.init()]
for item in paramClass {
       let temp = item as! NetWClass
       print(temp.name)
}

三,as?

as? 类型转换, 在类型转换失败的时候返回nil. 否则返回转换后的类型

class NetWClassA:NSObject{
    var name:String = "NetWClassA强制转换成功"
}
        
class NetWClassB:NSObject{
     var name:String = "NetWClassB强制转换成功"
}
        
        let ParamClassX:[Any] = [NetWClassA.init(), NetWClassB.init()]
        for item in ParamClassX {
            
        let temp = item as? NetWClassA
        if temp == nil{
           print(temp)
        }else{
           print((temp?.name)!)
        }
            
       let tempX = item as? NetWClassB
       if tempX == nil {
           print(tempX)
       }else{
           print((tempX?.name)!)
       }

你可能感兴趣的:(Swift4.2~as,as!,as?)