swiftcastingtypecast-operator

Why would I use typecasting in Swift?


Why would i be using typecasting in Swift?

I'm learning the language and I came across the subject of typecasting (e.g. down and upcasting etc.), but in my eyes it seems like a bit of a hassle. Why would i typecast an object? When would this be useful in real life applications or code? I've looked on the internet for a bit but I can not seem to find a unambiguous answer. I'm really stuck with this so some help would be great!

Thanks in advance!


Solution

  • The key case here is downcasting. You would do that because you might know what type an object really is, but the compiler doesn't know, so it won't let you send that type's messages to that object.

    Example:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let dest = segue.destination as? FlipsideViewController {
            dest.delegate = self
        }
    }
    

    segue.destination is typed as UIViewController; that is just a fact, and is not up to you, because a segue's destination needs to be able to be any kind of UIViewController.

    Only you know that this view controller is actually a FlipsideViewController. If you don't tell the compiler that, you can't set its delegate property (a plain vanilla UIViewController has no delegate property).

    So to sum up: the common downcasting situation is when a type needs to be declared as the superclass because any subclass needs to be acceptable, but then in a particular instance you know what subclass it is so you need to cast down to that.