Upcasting

Hi Community,

I do not find much about upcast in the book The Swift Programming Language.

Is the assignment "base = subclass" below still called upcast, and legal behavior in Swift?

Can I still use this, or should I use operators: is, as, as?, as!

class Base {
    func fun() { print("Hi Base") }
}

class Subclass: Base {
    override func fun() { print("Hi Subclass") }
}

var base = Base()
var subclass = Subclass()

base.fun()
base = subclass //upcast
base.fun()

//Hi Base
//Hi Subclass

What you call "upcast" is not, in fact, casting. It is simply assigning an instance of a subclass to a base class reference. There is no need for any use of is, as, as? and especially not as! operators. Any subclass is guaranteed to be assignable to a reference of its superclass.

The fun() method in Base is regarded as virtual and gets overridden but the version in Subclass

This principle applies to every language that supports OO that I have ever used. Look up any reference material on polymorphism for more explanation.

You can just as easily do :

var base: Base = Subclass()

base.fun()

… and get the expected result.

3 Likes
Terms of Service

Privacy Policy

Cookie Policy