Swift“as”和“as!”有什么区别?型铸造作业?

时间:2015-07-03 22:57:07

标签: swift types type-conversion

为什么在Swift中有asas!as?类型转换?

1 个答案:

答案 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