Type casting in swift : difference between is, as, as?, as!

What is the difference between is, as, as?, as! in swift? Well, lets check.

Abhimuralidharan
5 min readJul 14, 2017

Apple doc says: Type casting is a way to check the type of an instance, or to treat that instance as a different superclass or subclass from somewhere else in its own class hierarchy.

Type casting in Swift is implemented with the is and as operators. is is used to check the type of a value whereas as is used to cast a value to a different type.

Consider the following classs LivingBeing and two subclasses of LivingBeing named Human and Animal .

Now create a constant array called livingBeingArray with one Animal class object and one human class object. What do you think the type of this array created via type inference? It will be of type [LivingBeing] .

Swift’s type checker is able to deduce that Human and Animal have a common superclass of LivingBeing, and so it infers a type of [LivingBeing] for the livingBeingArray array.

The items stored in livingBeingArray are still Human and Animal instances behind the scenes. However, if you iterate over the contents of this array, the items you receive back…

--

--