Swift---19.類(lèi)型轉(zhuǎn)換

  • 類(lèi)型判斷:

如下例子,我們創(chuàng)建了一個(gè)Weather類(lèi),以及它的兩個(gè)子類(lèi)Rain,Snow,同時(shí)我們用一個(gè)數(shù)組存放兩個(gè)子類(lèi)的實(shí)例,因?yàn)樗麄兌紝儆?code>Weather類(lèi),所以他們可以放在一起.當(dāng)我們想要用他的時(shí)候,我們需要對(duì)他們的類(lèi)型做一個(gè)判斷
- #####"is":
使用"is"可以判斷一個(gè)實(shí)例是否屬于某個(gè)類(lèi)
- #####"as?/as!":
父類(lèi)向子類(lèi)轉(zhuǎn)換,這種轉(zhuǎn)換可能會(huì)失敗,所以返回的是可選類(lèi)型,所以一般使用as?來(lái)轉(zhuǎn)化,當(dāng)返回nil,表示轉(zhuǎn)化失敗.若使用as!,當(dāng)轉(zhuǎn)化失敗時(shí),編譯器會(huì)報(bào)錯(cuò)
- #####"Any","AnyObject"
- "Any":表示任意類(lèi)型的實(shí)例
- "AnyObject":表示任意類(lèi)類(lèi)型的實(shí)例
class Weather { var degree:Int init(degree:Int) { self.degree = degree } } class Rain : Weather { var status:String init(degree:Int,status:String) { self.status = status super.init(degree: degree) } } class Snow : Weather { var status:String init(degree:Int,status:String) { self.status = status super.init(degree: degree) } } var array = [Rain.init(degree: 22, status: "heavy"), Snow.init(degree: -1, status: "small")] for item in array { if item is Snow { print("snow") }else if item is Rain { print("rain") } } for item in array { if let instance = item as? Snow { print("snow") }else if let instance = item as? Rain { print("rain") } } //報(bào)錯(cuò) //let snow = array[1] as! Rain var anotherArray:[Any] = [Rain.init(degree: 22, status: "heavy"), Snow.init(degree: -1, status: "small"), 0, 0.0, 11, "3", (1.0,3.0), {(name:String)->String in "\(name)"}] for item in anotherArray { switch item { case 0 as Int: print("整型0") case 0 as Double: print("雙精度0") case let someString as String: print(someString) case let someInt as Int: print(someInt) case let strFunction as (String)->String: strFunction("hello") case let (x,y) as (Double,Double): print("元組(\(x),\(y))") case let snow as Snow: print("snow") case let rain as Rain: print("rain") default: break } }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容