Swift Type Casting

In swift, Type casting is the process in which we can convert the type of one object into another type. Using type casting we check the instance that it belongs to its superclass or subclass depend upon hierarchy. 

 

Swift allows two operators for the implementation of type casting is and as operator. Both operators are used to check and cast the value into different types. Type casting is also used to check whether type conforms to a protocol or not.

Swift Class Hierarchy for Type Casting

The major use of type casting operators is in a hierarchy of super and sub classes to check the type of particular class instance and to cast that class instance into another class within the same hierarchy.

 

Following is the example of defining a hierarchy of classes and an array that contains instances of classes to use it in type casting.

 

class Employee {

var name: String

init(name: String) {

self.name = name

}

}

class Departments: Employee {

var department: String

init(name: String, department: String) {

self.department = department

super.init(name: name)

}

}

class Financials: Employee {

var salary: Int

init(name: String, salary: Int) {

self.salary = salary

super.init(name: name)

}

}

let empdetails = [

Departments(name: "Suresh", department: "Software"),

Financials(name: "Suresh", salary: 10000),

Departments(name: "Trishika", department: "Healthcare"),

Financials(name: "Trishika", salary: 500000)

]

print(empdetails)

print(empdetails[0].name)

If you observe above example we defined a one super class (Employee) and two subclasses (Departments, Financials) and we created an instance which holds two Departments instances and two Financials instances.

 

When we run the above program in swift playground we will get a result like as shown below

 

[main.Departments, main.Financials, main.Departments, main.Financials]

Suresh

This is how we can define a hierarchy of classes to use it in type casting based on our requirements in swift programming language.

Swift Checking Type

In swift, we can do a type checking by using the type check operator (is). The type checking is used to check whether an instance is of a certain subclass type. If an instance belongs to that subclass type, the type check operator returns a true value. If it is not belong to the subclass type, it returns a false value.

 

Following is the example of checking the instance type using type check operator is in a swift programming language.

 

class Employee {

var name: String

init(name: String) {

self.name = name

}

}

class Departments: Employee {

var department: String

init(name: String, department: String) {

self.department = department

super.init(name: name)

}

}

class Financials: Employee {

var salary: Int

init(name: String, salary: Int) {

self.salary = salary

super.init(name: name)

}

}

let empdetails = [

Departments(name: "Suresh", department: "Software"),

Financials(name: "Suresh", salary: 10000),

Departments(name: "Trishika", department: "Healthcare"),

Financials(name: "Trishika", salary: 500000)

]

var deptCount = 0

var financeCount = 0

for item in empdetails {

if item is Departments {

deptCount += 1

} else if item is Financials {

financeCount += 1

}

}

print("The Employee Info contains \(deptCount) Departments and \(financeCount) Salaries")

If you observe above example we defined a one super class (Employee) and two subclasses (Departments, Financials) and we created an instance which holds two Departments instances and two Financials instances.

 

When we run the above program in swift playground we will get result like as shown below

 

The Employee Info contains 2 Departments and 2 Salaries

This is how we can check the type using for loop with is keyword in a swift programming language.

Swift Downcasting

In swift, Downcasting is the process in which we can downcast the instance to the subclass type with typecast operators like (as? Or as!). 

 

Generally, we can use a typecast operator as? when we are not sure if the downcast succeed or not. It will return an optional value of the type which we want to downcast whenever the down casting fails. 

 

We can use forced form of the type cast as! operator only when we are sure that downcast will always succeed. This type cast operator will throw a runtime error in case if we try to downcast an invalid class type.

 

Following is the example of iterating over each item of Employee in empdetails and prints each user details with salary and department information using type cast operator as? to check the downcast each time through the loop.

 

class Employee {

var name: String

init(name: String) {

self.name = name

}

}

class Departments: Employee {

var department: String

init(name: String, department: String) {

self.department = department

super.init(name: name)

}

}

class Financials: Employee {

var salary: Int

init(name: String, salary: Int) {

self.salary = salary

super.init(name: name)

}

}

 

let empdetails = [

Departments(name: "Suresh", department: "Software"),

Financials(name: "Suresh", salary: 10000),

Departments(name: "Trishika", department: "Healthcare"),

Financials(name: "Trishika", salary: 500000)

]

for item in empdetails {

if let dept = item as? Departments {

print("Name: \(dept.name), Department: \(dept.department)")

} else if let fina = item as? Financials {

print("Name: \(fina.name), Salary: \(fina.salary)")

}

}

If you observe the above example we used a type casting operator as? to downcast each item through the loop. Here we don’t know which item will come either Departments or Financials each time when we loop through items in Employee that’s the reason here we used type casting operator as?.

 

When we run the above program in swift playground we will get a result like as shown below

 

Name: Suresh, Department: Software

Name: Suresh, Salary: 10000

Name: Trishika, Department: Healthcare

Name: Trishika, Salary: 500000

This is how we can downcast to subclass type to get items using type cast operators as? or as! based on our requirements.

Swift Type Casting for Any and AnyObject

Swift provides type casting flexibility for nonspecific types. The two special types are

 

  • [Any]
  • [AnyObject]

Swift Any Type Casting

In swift, Any represent an instance of any type, even including functions. When we represent [Any] in array or dictionaries which means that we are telling the compiler that the elements in this list or array is not in the same data type. Unlike if we declare an array with String, compiler restricts the programmer to enter only strings, not integers. But [Any] gives us the flexibility to store any data type through it.

 

Following is the example of using [Any] type casting to store any data type of values in an instance.

 

class Employee {

var name: String

init(name: String) {

self.name = name

}

}

class Departments: Employee {

var department: String

init(name: String, department: String) {

self.department = department

super.init(name: name)

}

}

var items = [Any]()

items.append(34)

items.append(45.87)

items.append("Trishika Dasari")

items.append((453.05, 534.0))

items.append(Departments(name: "Suresh", department: "Software"))

for item in items {

switch item {

case let sInt as Int:

print("Integer Value : \(sInt)")

case let sDouble as Double:

print("Double Value : \(sDouble)")

case let sString as String:

print("String Value : \(sString)")

case let (x, y) as (Double, Double):

print("An (x, y) Values : \(x), \(y)")

case let dept as Departments:

print("Name: \(dept.name), Department: \(dept.department)")

default:

print("Nothing")

}

}

If you observe above example items array contains a different type of data type values like Int, String, Double, tuple and Departments. To know the type of values which stored in items array we must loop through an items array using for loop and finding an elements using switch case statements.

 

When we run the above program in swift playground we will get a result like as shown below

 

Integer Value : 34

Double Value : 45.87

String Value : Trishika Dasari

An (x, y) Values : 453.05, 534.0

Name: Suresh, Department: Software

This is how we can use [Any] type casting in application to store any type of values based on our requirements in swift programming language.

Swift AnyObject Type Casting

In swift, AnyObject is used to represent the instance of any class type which is derived from another class. In simplest word, we can say [AnyObject] is an alias to any data type from a class but it can’t share the root class. Mostly we use [AnyObject] type is when we working with APIs to fetch any array with a type of [AnyObject].

 

Following is the example of iterating over an each item of Employee in empdetails and prints each user details with salary and department information using typecast [AnyObject] and operator as?.

 

class Employee {

var name: String

init(name: String) {

self.name = name

}

}

class Departments: Employee {

var department: String

init(name: String, department: String) {

self.department = department

super.init(name: name)

}

}

class Financials: Employee {

var salary: Int

init(name: String, salary: Int) {

self.salary = salary

super.init(name: name)

}

}

 

let empdetails : [AnyObject] = [

Departments(name: "Suresh", department: "Software"),

Financials(name: "Suresh", salary: 10000),

Departments(name: "Trishika", department: "Healthcare"),

Financials(name: "Trishika", salary: 500000)

]

for item in empdetails {

if let dept = item as? Departments {

print("Name: \(dept.name), Department: \(dept.department)")

} else if let fina = item as? Financials {

print("Name: \(fina.name), Salary: \(fina.salary)")

}

}

If you observe above example we used [AnyObject] and typecasting operator as? to iterate through an each item.

 

When we run the above program in swift playground we will get a result like as shown below

 

Name: Suresh, Department: Software

Name: Suresh, Salary: 10000

Name: Trishika, Department: Healthcare

Name: Trishika, Salary: 500000

This is how we can do type casting using Any and AnyObject to store any type of elements in instances based on our requirements in swift programming language.