Downcasting with protocols and classes
The ComicCharacter
protocol defines one of the method requirements for the drawSpeechBalloon
method with destination
as an argument of the ComicCharacter
type, which is the same type that the protocol defines. The following is the first line in our sample code that called this method:
brian.drawSpeechBalloon(destination: merlin, message: "How do you do?")
We called the method defined within the AngryDog
class because brian
is an instance of AngryDog
. We passed an AngryDog
instance, merlin
, to the destination
argument. The method works with the destination
argument as an instance that conforms to the ComicCharacter
protocol; therefore, whenever we reference the destination variable, we will only be able to see what the ComicCharacter
type defines.
We can easily understand what happens under the hood when Swift downcasts a type from its original type to a target type, such as a protocol to which the class conforms. In this case, AngryDog
is downcasted...