Treating instances of a protocol type as a different subclass
Now, we will take advantage of the capability 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 doSomethingWith
method to the existing AngryCat
class. The code file for the sample is included in the swift_3_oop_chapter_05_11
folder:
public extension AngryCat { public func doSomethingWith(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.") } } ...