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?"
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?"
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.
number is an Int. It prints a message if true.let number: Any = 5 if number is Int { print("It's an Int") }
pet is typed as Animal, it holds a Dog instance, so is Dog returns true.class Animal {} class Dog: Animal {} let pet: Animal = Dog() print(pet is Dog) // true
text is a String or Int. Only the first is true.let text: Any = "Hello" print(text is String) // true print(text is Int) // false
This program creates a vehicle and checks its type using is. It prints the type found.
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") }
The is operator only checks type, it does not change the value.
Use as? or as! to cast after checking type with is.
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.
is operator do in Swift?is operatoris operator is used to check the type of a value in Swift.is only checks type and returns true or false.is operator = type check [OK]is checks type, not value or conversion [OK]is with type castingis compares valuesis to convert typesitem is of type String in Swift?is to check type, so item is String is correct.== compares values, as is for casting, and instanceof is not Swift syntax.is [OK]is for type checks, not as or == [OK]== instead of isis with asinstanceof in Swiftlet value: Any = 42
if value is Int {
print("Integer")
} else {
print("Not an Integer")
}value is declared as Any but holds the integer 42.is conditionvalue is Int checks if the value is an integer, which is true.is Int on 42 = true [OK]Any means not Intisis with castinglet obj: Any = "Hello"
if obj is String {
print(obj as String)
}as requires the compiler to know the type; here obj is Any.as? with optional binding or forced cast as!. Using as String alone causes error.as -> Option Aas? or as! for casting [OK]as? for safe cast, not plain as [OK]as without optional bindingas?is casts automaticallylet items: [Any] = [1, "two", 3.0, "four"], which Swift code correctly prints only the strings using the is operator?is operator checks type correctly; item is String returns true for strings.== String compares values, as String is invalid syntax here, and instanceof is not Swift.is to filter by type [OK]is to filter items [OK]instanceofPass the test and this pattern moves unknown