Type casting in swift : difference between is, as, as?, as!
What is the difference between is, as, as?, as! in swift? Well, lets check.
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
andas
operators.is
is used to check the type of a value whereasas
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
andAnimal
have a common superclass ofLivingBeing
, and so it infers a type of[LivingBeing]
for thelivingBeingArray
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…