Swift as、as!、as?三种类型转换操做符使用详解

  1. as 使用场合

(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
}
  1. as!使用场合 向下转型(Downcasting)时使用。因为是强制类型转换,若是转换失败会报 runtime 运行错误。
class Animal {}
class Cat: Animal {}
let animal :Animal  = Cat()
let cat = animal as! Cat
  1. 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")
}
相关文章
相关标签/搜索