Swift Type Casting (as, is, as?) Example

1. Introduction

Swift provides several operators that help in type checking and casting, allowing you to check the type of an instance or to treat an instance as a different superclass or subclass from somewhere else in its hierarchy.

- is: Used to check the type of an instance.

- as?: Used to downcast to a subclass, and it returns an optional value (returns nil if the downcast is not possible).

- as!: Used to force unwrap the result of a downcast. Be cautious with this, as it can cause a runtime crash if the downcast is not possible.

- as: Used for upcasting, which is casting a type to its superclass.

2. Source Code Example

class Animal {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class Bird: Animal {
    var wingSpan: Double
    init(name: String, wingSpan: Double) {
        self.wingSpan = wingSpan
        super.init(name: name)
    }
}

class Fish: Animal {
    var finCount: Int
    init(name: String, finCount: Int) {
        self.finCount = finCount
        super.init(name: name)
    }
}

let sparrow = Bird(name: "Sparrow", wingSpan: 30.0)
let salmon = Fish(name: "Salmon", finCount: 4)

let animals: [Animal] = [sparrow, salmon]

for animal in animals {
    if animal is Bird {
        print("\(animal.name) is a bird.")
    } else if animal is Fish {
        print("\(animal.name) is a fish.")
    }
}

if let bird = sparrow as? Bird {
    print("\(bird.name) has a wingspan of \(bird.wingSpan) cm.")
}

if let fish = salmon as? Fish {
    print("\(fish.name) has \(fish.finCount) fins.")
}

Output:

Sparrow is a bird.
Salmon is a fish.
Sparrow has a wingspan of 30.0 cm.
Salmon has 4 fins.

3. Step By Step Explanation

1. We define a base class Animal with a property name.

2. We then define two subclasses: Bird and Fish, each with properties specific to them (wingSpan and finCount respectively).

3. We create instances of Bird and Fish.

4. We have an array animals of type [Animal], which can hold instances of Animal and its subclasses.

5. We iterate through the animals array and use the is operator to check the type of each animal, printing an appropriate message based on its type.

6. We demonstrate the use of the as? operator by trying to downcast the sparrow and salmon instances to their respective types and then accessing their unique properties.

This example showcases how Swift’s type casting operators can be used for type checking and casting. It's crucial to ensure the safe and correct manipulation of types and classes within the Swift type system.


Comments