Swift Language Example of using a downcast on a function parameter involving subclassing


Example

A downcast can be used to make use of a subclass's code and data inside of a function taking a parameter of its superclass.

class Rat {
    var color = "white"
}

class PetRat: Rat {
    var name = "Spot"
}

func nameOfRat(🐭: Rat) -> String {
    guard let petRat = (🐭 as? PetRat) else {
        return "No name"
    }
    
    return petRat.name
}

let noName = Rat()
let spot = PetRat()

print(nameOfRat(noName))
print(nameOfRat(spot))