Swift: Test class type in the switch statement


In Swift, you can use the is keyword to test the class type of an object in a switch statement. Also, you will some examples of how to typecast an object to the expected type.

Here is an example to test primitive data types

In this example, you will check the type for primitive data types such as String, Int, Double, etc. You can use the switch statement to check multiple conditions like the below −

Example

import Foundation
func checkType(_ value: Any) {
   switch value {
      case is String: print("The value is String.")
      case is Int: print("The value is Int.")
      case is Int32: print("The value is Int32.")
      case is Double: print("The value is Double.")
      case is Bool: print("The value is Boolean.")
      default: print("The value is of some other type.")
   }
}
checkType(16)
checkType(16.0)
checkType("16")
checkType(true)
checkType(Float(16.0))

Output

The value is Int.
The value is Double.
The value is String.
The value is Boolean.
The value is of some other type.

In this example, the value is an instance of type "Any", and it will use the keyword of the switch statement to test the primitive type of the value. The first case block will execute if the value is an instance of String. If it's an instance of any other type, the other case block will execute and if it's none of the above, the default block will execute.

Here is an example to test custom types

In a similar way, you can check the type for custom type also. It means you can check the class type created by you.

Example

import Foundation
class Car {  
   let numberOfWheels: Int
   let colorCode: String
    
   init(wheels: Int, color: String) {
      self.numberOfWheels = wheels
      self.colorCode = color
   }
}
class Person {
   let name: String
   let age: Int
    
   init(name: String, age: Int) {
      self.name = name
      self.age = age
   }
}
class Student {
   var school: String
   var grade: Int
    
   init(school: String, grade: Int) {
      self.school = school
      self.grade = grade
   }
}
func checkType(_ object: Any) {
   switch object {
      case is Car: print("The object is a Car.")
      case is Person: print("The object is a Person.")
      case is Student: print("The object is a Student.")
      default: print("The object is of some other type.")
   }
}
let car = Car(wheels: 4, color: "red")
let person = Person(name: "Amit Yadav", age: 23)
let student = Student(school: "St. Primary School", grade: 5)
checkType(car)
checkType(student)
checkType(person)

Output

The object is a Car.
The object is a Student.
The object is a Person.

If you will see both examples, we are checking the type of given object or value. But if you want to typecast the given object to the expected type and use it later, it is recommended to use the type-casting method using as an operator. Using this method, you can typecast the object to access the properties.

Here is an example of using as operator

In Swift, there is another keyword “as” you can use to check the object type. This operator is used to typecast an object from one type to another type. It returns a casted instance of the desired type.

If the condition matches with true or the object is cast of a given type, return an instance otherwise returns nil, and the “if” condition will not execute.

Example

import Foundation
class Car {    
   let numberOfWheels: Int
   let colorCode: String
    
   init(wheels: Int, color: String) {
      self.numberOfWheels = wheels
      self.colorCode = color
   }
}
class Person {
   let name: String
   let age: Int
    
   init(name: String, age: Int) {
      self.name = name
      self.age = age
   }
}
class Student {
   var school: String
   var grade: Int
    
   init(school: String, grade: Int) {
      self.school = school
      self.grade = grade
   }
}
func checkType(_ object: Any) {
   switch object {       
      case let carObject as Car:
         print("The object is a Car type with \(carObject.numberOfWheels) wheels.")   
      case let personObject as Person:
         print("The object is a Person type with the name \(personObject.name).")       
      case let studentObject as Student:
         print("The object is a Student type with school \(studentObject.school).")
      default: print("The object is of some other type.")
   }
}
let car = Car(wheels: 4, color: "red")
let person = Person(name: "Amit Yadav", age: 23)
let student = Student(school: "St. Primary School", grade: 5)
checkType(car)
checkType(student)
checkType(person)

Output

The object is a Car type with 4 wheels.
The object is a Student type with school St. Primary School.
The object is a Person type with the name Amit Yadav.

Conclusion

In swift, you can use the “is” keyword to check the type of a class object. Many times, you might need to require the object type to perform an action or to execute the code accordingly.

If you want to check an object for multiple classes, you can use the switch statement with different cases. If the object does not match any of the classes, it will execute the default block. You can handle the code execution accordingly. Otherwise, you can check with the if-else statement. If a condition is matched, perform an action you want to perform.

Updated on: 28-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements