Swift as 向下转型的几种形式和用法

as?
for casts that are allowed to fail. This would happen if the object is nil or doesn’t have a type that is compatible with the one you’re trying to cast to. It will try to cast to the new type and if it fails, then no biggie. This cast returns an optional that you can unwrap with if let.
as!
for casts between a class and one of its subclasses. This is also known as a downcast. As with implicitly unwrapped optionals this cast is potentially unsafe and you should only use as! when you are certain it cannot possibly go wrong. You often need to use this cast when dealing with objects coming from UIKit and the other iOS frameworks. Better get used to all those exclamation marks!
as
for casts that can never possibly fail. Swift can sometimes guarantee that a type cast will always work, for example between NSString and String. In that case you can leave off the ? or the ! and just write as.

It can sometimes be confusing to decide which of these three cast operators you need. If so, just type “as” and Xcode will suggest the correct variant. But nine times out of ten it will be as!.有时候,这三种用法会容易混淆,Swift推荐使用as,但有时候用as!更合适

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值