何时在 swift 中使用三种不同形式的关键字 "as"

when to use three different form of keyword "as" in swift

我目前正在阅读 "swift programming language 2.1" 并且正在学习如何使用向下转换关键字 "as"。在书中,as有三种不同的形式:as,as?并作为!。我知道什么时候使用 as?并作为!但无法确定何时使用 "as"。有人有什么建议吗?如果建议附带代码就更好了。在此先感谢您的帮助!

为您提供一些代码示例。我们可以使用 as 进行向上转换。参考代码示例来自此 article.

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