Downcasting optionals in Swift: as? Type, or as! Type?

The practical difference is this: var optionalString = dict[“SomeKey”] as? String optionalString will be a variable of type String?. If the underlying type is something other than a String this will harmlessly just assign nil to the optional. var optionalString = dict[“SomeKey”] as! String? This says, I know this thing is a String?. This too … Read more

downcast and upcast

That is correct. When you do that you are casting it it into an employee object, so that means you cannot access anything manager specific. Downcasting is where you take a base class and then try and turn it into a more specific class. This can be accomplished with using is and an explicit cast … Read more

Explicit type casting example in Java

Reference vs Object vs Types The key, for me, is understanding the difference between an object and its references, or put in other words the difference between an object and its types. When we create an object in Java, we declare its true nature, which will never change (e.g. new Truck()). But any given object … Read more

What is the difference between up-casting and down-casting with respect to class variable

Upcasting is casting to a supertype, while downcasting is casting to a subtype. Upcasting is always allowed, but downcasting involves a type check and can throw a ClassCastException. In your case, a cast from a Dog to an Animal is an upcast, because a Dog is-a Animal. In general, you can upcast whenever there is … Read more