0
0
Swiftprogramming~5 mins

Is operator for type checking in Swift

Choose your learning style9 modes available
Introduction

The is operator helps you check if a value belongs to a certain type. It is like asking, "Is this thing a kind of that?"

When you want to check if an object is a specific class before using it.
When you have a list of mixed types and want to find all items of one type.
When you want to safely cast an object after confirming its type.
When you want to run different code depending on the type of a value.
Syntax
Swift
value is TypeName

The is operator returns true if value is of the specified TypeName or a subclass of it.

It is often used in if statements to check types before casting.

Examples
This checks if number is an Int. It prints a message if true.
Swift
let number: Any = 5
if number is Int {
    print("It's an Int")
}
Even though pet is typed as Animal, it holds a Dog instance, so is Dog returns true.
Swift
class Animal {}
class Dog: Animal {}

let pet: Animal = Dog()
print(pet is Dog)  // true
Checks if text is a String or Int. Only the first is true.
Swift
let text: Any = "Hello"
print(text is String)  // true
print(text is Int)     // false
Sample Program

This program creates a vehicle and checks its type using is. It prints the type found.

Swift
class Vehicle {}
class Car: Vehicle {}
class Bike: Vehicle {}

let myVehicle: Vehicle = Car()

if myVehicle is Car {
    print("This is a Car")
} else if myVehicle is Bike {
    print("This is a Bike")
} else {
    print("Unknown vehicle")
}
OutputSuccess
Important Notes

The is operator only checks type, it does not change the value.

Use as? or as! to cast after checking type with is.

Summary

The is operator checks if a value is of a certain type.

It returns true or false and helps write safe code.

Use it before casting or running type-specific code.