(1)从派生类转化为基类,向上转型 (upcasts)code
class Animal {} class Cat: Animal {} let cat = Cat() let animal = cat as Animal
(2)消除二义性,数值类型转换对象
let num1 = 42 as CGFloat let num2 = 42 as Int let num3 = 42.5 as Int let num4 = (42 / 2) as Double
(3)switch 语句中进行模式匹配 若是不知道一个对象是什么类型,你能够经过switch语法检测它的类型,而且尝试在不一样的状况下使用对应的类型进行相应的处理it
switch animal { case let cat as Cat: print("若是是Cat类型对象,则作相应处理") case let dog as Dog: print("若是是Dog类型对象,则作相应处理") default: break }
class Animal {} class Cat: Animal {} let animal :Animal = Cat() let cat = animal as! Cat
let animal:Animal = Cat() if let cat = animal as? Cat{ print("cat is not nil") } else { print("cat is nil") }