Swift "as" 和 "as!" 类型转换操作有什么区别?

What is the difference between Swift "as" and "as!" type casting operations?

为什么 Swift 中存在 as vs. as! vs. as? 类型转换?

as是编译时强制转换

as?as! 是运行时转换

  • as? 将投射,如果无法投射,将 return 可选(无)
  • 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