Table of contents
1.
Introduction
2.
Type Casting
3.
Defining a Class Hierarchy
3.1.
Code:
3.2.
Output:
4.
Type Checking
4.1.
Code:
4.2.
Output:
5.
Downcasting
5.1.
Code:
5.2.
Output:
6.
Frequently Asked Questions
6.1.
What is Upcasting and Downcasting in Swift?
6.2.
What is the difference between any and AnyObject in Swift?
6.3.
What is a guard in Swift?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Swift Type Casting

Author Akshit Pant
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Typecasting is used in Swift4 to validate the type of an instance.

Let us assume that you have a basic understanding of programming languages and are familiar with basic Swift Introduction. In this blog, we will be covering Swift Type Casting, its components, and its implementation in our code. But before that, you can also check out our articles on Swift Arrays, Swift Strings, Swift Tuples and Swift Methods etc.

So let us start with the basic idea of what Typecasting in Swift is.

Type Casting

To validate the type of an instance 'Type Casting' comes into play in Swift 4 language. It is used to check whether the instance type belongs to a particular superclass or subclass or is defined in its own hierarchy.


Swift 4 type casting provides two operators: 'is' to check the type of a value and 'as' and to cast the type value to a different type. Typecasting also checks whether the instance type follows a particular protocol conformance standard.

Defining a Class Hierarchy

Typecasting is used to check the type of instances to find out whether it belongs to a particular class type. Also, it checks the hierarchy of classes and their subclasses to check and cast those instances to make it the same hierarchy.

Code:

class Subjects {
   var physics: String
   init(physics: String) {
      self.physics = physics
   }
}

class Chemistry: Subjects {
   var equations: String
   init(physics: String, equations: String) {
      self.equations = equations
      super.init(physics: physics)
   }
}

class Maths: Subjects {
   var formulae: String
   init(physics: String, formulae: String) {
      self.formulae = formulae
      super.init(physics: physics)
   }
}

let sa = [ Chemistry(physics: "solid physics", equations: "Hertz"),
   Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")]

let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
print("Instance physics is: \(samplechem.physics)")
print("Instance equation is: \(samplechem.equations)")

let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
print("Instance physics is: \(samplemaths.physics)")
print("Instance formulae is: \(samplemaths.formulae)")

Output:

Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz

Type Checking

Type checking is done with the 'is' operator. The 'is' type check operator checks whether the instance belongs to a particular subclass type and returns 'true' if it belongs to that instance else it will return 'false'.|

Code:

class Subjects {
   var physics: String
   init(physics: String) {
      self.physics = physics
   }
}

class Chemistry: Subjects {
   var equations: String
   init(physics: String, equations: String) {
      self.equations = equations
      super.init(physics: physics)
   }
}

class Maths: Subjects {
   var formulae: String
   init(physics: String, formulae: String) {
      self.formulae = formulae
      super.init(physics: physics)
   }
}

let sa = [
   Chemistry(physics: "solid physics", equations: "Hertz"),
   Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz"),
   Chemistry(physics: "Thermo physics", equations: "Decibels"),
   Maths(physics: "Astro Physics", formulae: "MegaHertz"),
   Maths(physics: "Differential Equations", formulae: "Cosine Series")]

let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
print("Instance physics is: \(samplechem.physics)")
print("Instance equation is: \(samplechem.equations)")

let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
print("Instance physics is: \(samplemaths.physics)")
print("Instance formulae is: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0
for item in sa {
   if item is Chemistry {
      ++chemCount
   } else if item is Maths {
      ++mathsCount
   }
}

print("Subjects in chemistry contains \(chemCount) topics and maths contains \(mathsCount) topics")

Output:

Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Subjects in chemistry contains 2 topics and maths contains 3 topics

Downcasting

Downcasting the subclass type can be done with two operators (as? and as!).'as?' returns an optional value when the value returns nil. It is used to check successful downcast.

'as!' returns force unwrapping as discussed in the optional chaining when the downcasting returns nil value. It is used to trigger runtime error in case of downcast failure

Code:

class Subjects {
   var physics: String
   init(physics: String) {
      self.physics = physics
   }
}

class Chemistry: Subjects {
   var equations: String
   init(physics: String, equations: String) {
      self.equations = equations
      super.init(physics: physics)
   }
}

class Maths: Subjects {
   var formulae: String
   init(physics: String, formulae: String) {
      self.formulae = formulae
      super.init(physics: physics)
   }
}

let sa = [
   Chemistry(physics: "solid physics", equations: "Hertz"),
   Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz"),
   Chemistry(physics: "Thermo physics", equations: "Decibels"),
   Maths(physics: "Astro Physics", formulae: "MegaHertz"),
   Maths(physics: "Differential Equations", formulae: "Cosine Series")]

let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
print("Instance physics is: \(samplechem.physics)")
print("Instance equation is: \(samplechem.equations)")

let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
print("Instance physics is: \(samplemaths.physics)")
print("Instance formulae is: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0

for item in sa {
   if let print = item as? Chemistry {
      print("Chemistry topics are: '\(print.physics)', \(print.equations)")
   } else if let example = item as? Maths {
      print("Maths topics are: '\(example.physics)', \(example.formulae)")
   }
}

Output:

Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Chemistry topics are: 'solid physics', Hertz
Maths topics are: 'Fluid Dynamics', Giga Hertz
Chemistry topics are: 'Thermo physics', Decibels
Maths topics are: 'Astro Physics', MegaHertz
Maths topics are: 'Differential Equations', Cosine Series

Frequently Asked Questions

What is Upcasting and Downcasting in Swift?

Downcasting is the opposite of upcasting. When you upcast, you cast from a subclass to a superclass (upwards) When you downcast, you cast from a superclass to a subclass (downwards)


What is the difference between any and AnyObject in Swift?

AnyObject is only for reference types (classes), Any is for both value and reference types. So you should go for [String: Any] . Swift provides two special types for working with nonspecific types: Any can represent an instance of any type at all, including function types.


What is a guard in Swift?

In Swift, we use the guard statement to transfer program control out of scope when certain conditions are not met. The guard statement is similar to the if statement with one major difference. The if statement runs when a certain condition is met. However, the guard statement runs when a certain condition is not met.

Conclusion

In this article, we learned about Type Casting in Swift and its working implementation by showcasing a working example.

However, learning never stops, and there is more to learn. So head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications.

We hope this article has helped you enhance your knowledge as a Dart beginner. If you want to learn more, check out our article on environment setup and Competitive Programming articles. Do upvote this article to help other ninjas grow.

Happy Coding!

Live masterclass