为什么在Swift中有as
与as!
与as?
类型转换?
答案 0 :(得分:5)
as
是编译时间
as?
和as!
是运行时强制转换
as?
将被施放,如果施放不可能将返回Optional(nil)as!
将被施放,如果不可能施放会因运行时错误而崩溃示例:
class Music { }
class Pop: Music { }
class Rock: Music { }
Pop() as Music // OK, some might disagree but Music *is* a super class of Pop
Pop() as Rock // Compile error: 'Pop' is not convertable to 'Rock'
let pop: AnyObject = Pop()
pop as Music // Compile error: 'AnyObject' is not convertible to 'Music'
pop as? Pop // Pop
pop as! Pop // Pop
pop as? Music // Pop
pop as! Music // Pop
pop as? Rock // nil
pop as! Rock // Runtime error signal SIGABRT