Using isKindOfClass with Swift


In this article, you are going to learn how to use isKindOfClass in swift with some different examples. It is required many times you need to check the type of a class to perform specific code accordingly.

What is “isKindOfClass”?

The isKind(of:) method can be used for checking the object type. You can check if an object is an instance of a given type. You can check it for a class or subclass depending on the boolean value returned.

In Swift 5, the isKind(of:) method has been replaced by the is an operator and the is a keyword. The is operator is used to checking if an instance is of a certain type by returning the boolean value.

Example 

The following example demonstrates the same.

import Foundation
let object: Any = "This is a string message."
if object is String {
   print("Object is a type of string.")
} else {
   print("Object is not a type of string.")
}

Output

Object is a type of string.

Here is another example of an array of strings

In this example, you will check an object of type array of strings. Yes, this is possible to check the array or dictionary type also in Swift.

Example 

import Foundation
let object: [Any] = ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
if object is [String] {
   print("Object is the type of an array of strings.")
} else {
   print("Object is not the type of an array of strings.")
}

Output

Object is the type of an array of strings.

An alternate approach to checking the type

In this approach, you can use the Optional Binding method to check the type of an object. It is also recommended to check the type. Here is an example of checking type using Optional binding −

Example 

import Foundation
let object: [Any] = ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
if let array = object as? [String] {
   print("Output array: \(array)")
   print("Object is the type of an array of strings.")
} else {
   print("Object is not the type of an array of strings.")
}

Output

Output array: ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
Object is the type of an array of strings.

Conclusion

It is known that the is operator is used to checking the type of an instance. Alternatively, you can use the optional binding approach for the same purpose.

You can use the “is” operator to check the type of an instance before performing an operation. Incase you have a collection of objects and want to perform different actions based on the type of each object.

In addition, you can use the “as” operator to typecast an instance to access the properties and methods of that type. In order to handle the failure condition when an object is not casted of required type.

Updated on: 28-Feb-2023

595 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements