Swift: Type Casting

Type Casting:

Using type casting you will get to know about the type of an instance and at the same time, you can treat as a different super class or subclass hierarchy from its own class hierarchy.

We use two different operators to do type casting.

  1. as
  2. is

It can be checked for protocol conformance as well.

we will see with an example:





    we created an array of with objects which can have Movie and Song object.




However, if you iterate over the contents of this array, the items you receive back are typed as MediaItem, and not as Movie or Song. Checked the below image


and if you need to use contents of the array then you have type cast or downcast in a different type.

Checking Type:

Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.

for item in library {
    if item is Movie { // return true if item is Movie type
        // do
    } else if item is Song { // return true if item is Song type
        // do
    }
}

Downcasting:

A variable and a constant of a certain type may be different types behind scene using type casting.  You can do a type cast to subclass type by using downcasting using as "as?" or "as!".

As downcasting can fail and run time so we can use two different ways to handle it.

The conditional form as "as?" and forced form as "as!".

The conditional form, as? returns an optional value of the type you are trying to downcast to. The forced form, as!, attempts the downcast and force-unwraps the result as a single compound action.

Use the conditional form of the type cast operator (as?) when you are not sure if the downcast will succeed. This form of the operator will always return an optional value, and the value will be nil if the downcast was not possible. This enables you to check for a successful downcast.

Use the forced form of the type cast operator (as!) only when you are sure that the downcast will always succeed. This form of the operator will trigger a runtime error if you try to downcast to an incorrect class type.



The example starts by trying to downcast the current item as a Movie. Because item is a MediaItem instance, it’s possible that it might be a Movie; equally, it’s also possible that it might be a Song, or even just a base MediaItem. Because of this uncertainty, the as? form of the type cast operator returns an optional value when attempting to downcast to a subclass type. The result of item as? Movie is of type Movie?, or “optional Movie”.




NOTE
Casting does not actually modify the instance or change its values. The underlying instance remains the same; it is simply treated and accessed as an instance of the type to which it has been cast.

Type Casting for Any and AnyObject

  • Any can represent an instance of any type at all, including function types.
  • AnyObject can represent an instance of any class type.
  1. var things = [Any]() will create a array which can hold different type of data

To discover the specific type of a constant or variable that is known only to be of type Any or AnyObject, you can use an is or as pattern.

Note:

The Any type represents values of any type, including optional types. Swift gives you a warning if you use an optional value where a value of type Any is expected. 




Wrapping:

That's all from the type casting in Swift. Hope you will be clear. Please, do share any question and feedback. 
Read the last post regarding Optional Chaining

Happy Coding 😊


Comments

Popular posts from this blog

Copy Vs Mutable Copy in iOS

How to Disable iOS/iPad App availability on Mac Store, Silicon?

Closures in Swift - Part 1