Max*_*ler 0 types type-conversion swift
为什么在Swift 中有asvs as!vs. as?类型转换?
as 是编译时间
as?并且as!是运行时强制转换
as? 将施放,如果施放不可能将返回可选(零)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
Run Code Online (Sandbox Code Playgroud)