【问题标题】:What is the difference between Swift "as" and "as!" type casting operations?Swift“as”和“as!”有什么区别?类型铸造操作?
【发布时间】:2015-07-03 22:57:07
【问题描述】:

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

【问题讨论】:

标签: swift types type-conversion


【解决方案1】:

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

【讨论】:

  • 我不会强迫as?as? 是可选的。 asas! 是强制的,as 是安全的,as! 是不安全的。
  • @nhgrif 我认为你对强制分类是正确的,我会重写我的答案。
猜你喜欢
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 2010-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多