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!更合适

你可能感兴趣的:(Swift,swift)