Now, we will take advantage of the possibility that Swift offers us to extend an existing class to add specific members. In this case, we will add an instance method to the previously defined AngryCat
class. The following lines add the doSomethingWithAnAngryCat
method to the existing AngryCat
class:
public extension AngryCat { public func doSomethingWithAnAngryCat(cat: AngryCat) { if let angryCatAlien = cat as? AngryCatAlien { angryCatAlien.appear() } else if let angryCatKnight = cat as? AngryCatKnight { angryCatKnight.unsheathSword() } else if let angryCatWizard = cat as? AngryCatWizard { print("My spell power is \(angryCatWizard.spellPower)") } else { print("This AngryCat doesn't have cool skills.") } } }
The doSomethingWithAnAngryCat
method receives an AngryCat
instance (cat
) and uses the conditional type casting operator (as?
) to...