(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") }