0Pricing
Swift Academy · Lesson

Checking Types with is

Test an instance's type before casting.

The is Operator

The type-check operator is returns a Bool telling you whether an instance is of a given type (or subtype). It does not cast; it just tests.

class Animal {
    let name: String
    init(name: String) { self.name = name }
}
class Dog: Animal {
    func bark() -> String { return name + " says Woof" }
}
class Cat: Animal {
    func meow() -> String { return name + " says Meow" }
}
let a: Animal = Dog(name: "Rex")
print(a is Dog)
print(a is Cat)

Testing Subtype Membership

is is true when the instance is exactly that type or any subclass of it. A Dog is an Animal.

class Animal {
    let name: String
    init(name: String) { self.name = name }
}
class Dog: Animal {
    func bark() -> String { return name + " says Woof" }
}
class Cat: Animal {
    func meow() -> String { return name + " says Meow" }
}
let a: Animal = Dog(name: "Rex")
print(a is Animal)
print(a is Dog)

All lessons in this course

  1. Upcasting and Downcasting Basics
  2. Conditional Casting with as?
  3. Forced Casting with as! and Its Risks
  4. Checking Types with is
← Back to Swift Academy