Reputation: 73
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!
Upvotes: 4
Views: 235
Reputation: 535304
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.
Upvotes: 6
Reputation: 1058
Typecasting is used when you are not sure about the type of any variable or class. Suppose a variable value is setting from the server response . And it can be of multiple object type like String , Int , Double. Then you need typecasting to know what exactly type you are looking for.
Upvotes: 0