Declaring compound assignment operator functions

We also want to be able to increase the value of the age property of the different Animal instances by using the addition assignment operator (+=). This operator is one of the compound assignment operators that Swift provides and it combines assignment (=) with the addition operator (+).

Tip

Swift 3 removed both the pre-increment, post-increment, pre-decrement, and post-decrement operators. In other words, we cannot use ++ and -- in Swift 3. We might define a prefix increment and a postfix increment to increase the value of the age property, but it doesn't make sense to define an operator that Swift 3 has removed. Instead, we will use the addition assignment operator.

We have to declare an operator function with += as its name, specify the Animal type for the left argument, and specify the Int type for the right argument. Thus, we have left and right as the arguments for the operator function. In this case, the function doesn't return a value and only uses the += operator to the age property for the Animal instance received in the left argument.

Let's consider that we have an instance of Animal, or any of its subclasses, named animal1. If we enter animal1 += 2 in the Playground, Swift will invoke the += operator function with left equal to animal1 and right equal to 2.

We must add the following lines to make it possible to use the addition assignment operator to add an Int value to the value of the age property of an Animal instance. The code file for the sample is included in the swift_3_oop_chapter_04_12 folder:

    public func += (left: Animal, right: Int) { 
      left.age += right 
   } 

The following lines print the age for pluto--an instance of TerrierDog--and then apply the += operator and print the new age. Remember that we created an operator function that Swift invokes under the hood whenever we use the operator with an Animal instance on the left and an Int on the right. The code file for the sample is included in the swift_3_oop_chapter_04_12 folder:

    pluto.printAge() 
    pluto += 2 
    pluto.printAge() 

The following lines show the output generated by the preceding code:

    I am 7 years old. 
    I am 9 years old. 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.213.235