Declaring operator functions for specific subclasses
We already declared an operator function that allows any instance of Animal
or its subclasses to use the postfix increment (++
) operator. However, sometimes we want to specify a different behavior for one of the subclasses and its subclasses.
For example, we might want to express the age of dogs in the age
value that is equivalent to humans. We can declare an operator function for the postfix increment (++
) operator that receives a Dog
instance as an argument and increments the age value 7
years instead of just one. The following lines show the code that achieves this goal. The code file for the sample is included in the swift_3_oop_chapter_04_14
folder:
public postfix func ++ (dog: Dog) { dog.age += 7 }
The following lines create an instance of the SmoothFoxTerrier
class named goofy
, print the age for goofy
, apply the postfix ++
operator, and print the new age. Because SmoothFoxTerrier
is a subclass of Dog...