Type Handling

Tutorial 4 of 4

1. Introduction

This tutorial aims to help you understand type casting in Swift, a powerful feature that enables you to inspect the type of an instance or convert an instance of a class into one of its superclass or subclass.

By the end of this tutorial, you will be able to:

  • Understand the concept of type casting in Swift
  • Use type casting to check the type of an instance
  • Use type casting to treat an instance as a different superclass or subclass

Prerequisites: Basic knowledge of Swift programming language and object-oriented programming.

2. Step-by-Step Guide

In Swift, type casting is done with the is and as operators. These two operators provide a simple and readable way to check the type of a value or cast a value to a different type.

is Operator

The is operator checks whether an instance is of a certain subclass type.

let someInstance: SuperClass
...
if someInstance is SubClass {
    // someInstance is a SubClass
}

as? and as! Operators

The as? and as! operators are used to downcast to a subclass type. The as? version returns an optional value of the type you are trying to downcast to, and as! force unwraps the result.

let someInstance: SuperClass
...
if let someSubClass = someInstance as? SubClass {
    // someInstance is a SubClass and someSubClass is of type SubClass
}

3. Code Examples

Checking instance type with is

class Animal {
}

class Bird: Animal {
}

let sparrow = Bird()

if sparrow is Bird {
    print("Sparrow is a Bird") // Prints "Sparrow is a Bird"
}

Downcasting with as? and as!

class Animal {
}

class Bird: Animal {
    var canFly: Bool = false
}

let someAnimal: Animal = Bird()

if let bird = someAnimal as? Bird {
    print(bird.canFly) // Prints "false"
}

In this case, someAnimal was actually an instance of Bird, so the downcasting succeeded.

4. Summary

In this tutorial, we learned about type casting in Swift using is, as?, and as! operators. These operators allow us to check the type of an instance or to treat an instance as a different superclass or subclass from somewhere else in its own class hierarchy.

To continue your learning journey, you can learn more about Swift's type system, inheritance, and polymorphism.

5. Practice Exercises

  1. Exercise 1: Create a class Vehicle and two subclasses Car and Bike. Create an array of Vehicle and fill it with instances of Car and Bike. Use the is operator to find out the type of each instance in the array.

  2. Exercise 2: Continue from the previous exercise. Use the as? operator to downcast each instance in the array to Car and Bike. If the downcast is successful, print a specific message for each type.

Solutions:

// Exercise 1
class Vehicle {
}

class Car: Vehicle {
}

class Bike: Vehicle {
}

let vehicles: [Vehicle] = [Car(), Bike(), Car(), Bike()]

for vehicle in vehicles {
    if vehicle is Car {
        print("This is a car.")
    } else if vehicle is Bike {
        print("This is a bike.")
    }
}

// Exercise 2
for vehicle in vehicles {
    if let car = vehicle as? Car {
        print("We've got a car here.")
    } else if let bike = vehicle as? Bike {
        print("We've got a bike here.")
    }
}

Keep practicing and exploring more about Swift's type system. Happy coding!