as operator

Swift 1.2 separates the notions of guaranteed conversion and forced conversion into two distinct operators. Guaranteed conversion is still performed with the as operator, but forced conversion now uses the as! operator. The ! is meant to indicate that the conversion may fail. This way, you know at a glance which conversions may cause the program to crash.

class Animal {}
class Dog: Animal {}

let a: Animal = Dog()
a as Dog        // now raises the error:  "'Animal is not convertible to 'Dog';
                // ... did you mean to use 'as!' to force downcast?"

a as! Dog       // forced downcast is allowed

let d = Dog()
d as Animal     // upcast succeeds
Reference

https://developer.apple.com/swift/blog/?id=23

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 寻龙诀向我们证明了一件事:无论什么人,都有逗逼搞笑的一面。 这不仅能活跃气氛,还能推进剧情发展。最主要的,当角色开...
    聂经阅读 5,439评论 12 9
  • 总说走一步看一步 觉得这样的态度太随意太懒散没给自己做心理建设的机会 又说走一步看三步 觉得这么厉害不是我能做到的...
    628d30df06c8阅读 1,475评论 0 0
  • svn info 文件路径地址 比如:svn info jiehun-dp/modules/default/con...
    AriesDongs阅读 2,642评论 0 0
  • 本来是想写一些攻略的,但是想想微博上的攻略足够用了,我写的也比不上网络上的,况且我只去了那些我感兴趣的景点,而且大...
    MeV七七阅读 1,625评论 0 3