Type casting is a method used to check the type of a variable or to treat it as a different superclass/subclass. Swift implements type casting using is
and as
operators.
The keyword is
can be used to check the type of a variable.
var aVariable:Any = 4if aVariable is Int {print(aVariable, "is an integer")} else {print(aVariable, "is not an integer")}if aVariable is String {print(aVariable, "is a string")} else {print(aVariable, "is not a string")}
Any
.aVariable
is an integer and print the appropriate message.aVariable
is a string and print the appropriate message.A variable of a class may refer to an instance of its subclass or superclass. The keyword as
can be used to upcast or downcast a variable. Upcasting is treating that variable as a superclass instance, while downcasting is treating it as a subclass instance.
There are two cast operators used for this:
as?
: This operator is used when we are not sure if the downcast will succeed. If the downcast succeeds, it will return an optional value of the type we're trying to downcast to. Otherwise, it will just return nil
.as!
: This operator is used when we know that the downcast will always succeed. If it does not succeed, it will throw a runtime error.class Person {var name: Stringinit(name: String) {self.name = name}}class Employee: Person {var salary: Intinit(name: String, salary: Int) {self.salary = salarysuper.init(name:name)}}class Student: Person {var rollNumber: Intinit(name: String, rollNumber: Int) {self.rollNumber = rollNumbersuper.init(name:name)}}let anEmployee = Employee(name: "Ali", salary: 400)let aStudent = Student(name: "Educative", rollNumber: 500)// Forcing upcast to personlet personOne = anEmployee as Personlet personTwo = aStudent as Person// checking downcasting with as?print(personOne as? Student ?? "Person One is not a student")print(personTwo as? Student ?? "Person Two is not a student")
Person
, Student
, and Employee
. The classes Student
and Employee
inherit from the Person
class.Employee
and Student
classes and then upcast them to the Person
class using the as
operator.as?
to check if personOne
and personTwo
are instances of the Student
class. The hard-coded string is the default value returned by ??
in case it gets a Nil
. Otherwise, it returns the downcasted optional value of the class, which we can see when we run the code.Free Resources