O'Reilly logo

Swift 3 ObjectOriented Programming - Second Edition by Gastón C. Hillar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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)") ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required