Search code examples
swiftsubclasssuperclassdowncast

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


I'm currently reading "swift programming language 2.1" and is learning how to use the downcasting keyword "as". In the book, there are three different form of as: as, as? and as!. I understand when to use as? and as! but is having trouble figuring out when to use "as". Does anyone has any suggestions? It would be even better if there is code accompanying the suggestions. Thanks in advance for any help!


Solution

  • Some code example for you. We could use as for upcast. Reference code example is from this 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