Swift---19.类型转换

2017-03-06  本文已影响12人  阿丶伦

如下例子,我们创建了一个Weather类,以及它的两个子类Rain,Snow,同时我们用一个数组存放两个子类的实例,因为他们都属于Weather类,所以他们可以放在一起.当我们想要用他的时候,我们需要对他们的类型做一个判断
- #####"is":
使用"is"可以判断一个实例是否属于某个类
- #####"as?/as!":
父类向子类转换,这种转换可能会失败,所以返回的是可选类型,所以一般使用as?来转化,当返回nil,表示转化失败.若使用as!,当转化失败时,编译器会报错
- #####"Any","AnyObject"
- "Any":表示任意类型的实例
- "AnyObject":表示任意类类型的实例
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") } } //报错 //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 } }

上一篇下一篇

猜你喜欢

热点阅读