swift 之 as、as!、as?

时间:2023-03-09 16:14:51
swift 之 as、as!、as?

1,as使用场合
(1)从派生类转换为基类,向上转型(upcasts)

 class Animal {}
class Cat: Animal {}
let cat = Cat()
let animal = cat as Animal
(2)消除二义性,数值类型转换
 let num1 =  as CGFloat
let num2 = as Int
let num3 = 42.5 as Int
let num4 = ( / ) as Double

(3)switch 语句中进行模式匹配
如果不知道一个对象是什么类型,你可以通过switch语法检测它的类型,并且尝试在不同的情况下使用对应的类型进行相应的处理。

 switch animal {
case let cat as Cat:
print("如果是Cat类型对象,则做相应处理")
case let dog as Dog:
print("如果是Dog类型对象,则做相应处理")
default: break
}
2,as!使用场合

向下转型(Downcasting)时使用。由于是强制类型转换,如果转换失败会报 runtime 运行错误。

 class Animal {}
class Cat: Animal {}
let animal :Animal = Cat()
let cat = animal as! Cat
3,as?使用场合

as? 和 as! 操作符的转换规则完全一样。但 as? 如果转换不成功的时候便会返回一个 nil 对象。成功的话返回可选类型值(optional),需要我们拆包使用。
由于 as? 在转换失败的时候也不会出现错误,所以对于如果能确保100%会成功的转换则可使用 as!,否则使用 as?

 let animal:Animal = Cat()

 if let cat = animal as? Cat{
print("cat is not nil")
} else {
print("cat is nil")
}
注释:派生类:

二义性:
二义性问题
1.在继承时,基类之间、或基类与派生类之间发生成员同名时,将出现对成员访问的不确定性——同名二义性。
2.当派生类从多个基类派生,而这些基类又从同一个基类派生,则在访问此共同基类中的成员时,将产生另一种不确定性——路径二义性。