Transforming values with setters and getters

We can define a property with a setter method that transforms the values that will be set as valid values for a related property. The getter method would just need to return the value of the related property to generate a property that will always have valid values even when it is initialized. This way, we can make sure that whenever we require the property value, we will retrieve a valid value.

The following code replaces the previously declared runningSpeedScore property declaration that worked with a property observer, specifically, a didSet method. In this case, the setter transforms the values lower than 0 to 0 and values higher than 50 to 50. The setter stores either the transformed or original value that is in a valid range in the related runningSpeedScoreField property. The getter returns the value of the related runningSpeedScoreField property, that is, the private property that always stores a valid value. We have to replace the previous code, which declared the runningSpeedScore property, with the new code within the SuperHero class. The code file for the sample is included in the swift_3_oop_chapter_03_12 folder:

    private var runningSpeedScoreField: Int = 0 
    public var runningSpeedScore: Int { 
      get { 
        return runningSpeedScoreField 
      } 
      set { 
        if (newValue < 0) { 
          runningSpeedScoreField = 0 
        } else if (newValue > 50) { 
          runningSpeedScoreField = 50 
        } else { 
          runningSpeedScoreField = newValue 
        } 
      } 
    } 

Now, let's execute the following lines in the Playground. Enter the lines after the code that creates the new version of the SuperHero class. The code file for the sample is included in the swift_3_oop_chapter_03_11 folder:

    var superFlash = SuperHero(name: "Flash", 
    birthYear: 1972, sneakers: "Flash running", 
    runningSpeedScore: 135) 
    print(superFlash.runningSpeedScore) 

If we execute the following lines, the printed value will be 50, and the property will be initialized with a valid value because the code defined in the setter method will transform 135 into the maximum accepted value, which is 50, as seen in the following screenshot:

Transforming values with setters and getters

Tip

When we initialize a property that has a setter method, Swift calls the setter for the initialization value.

..................Content has been hidden....................

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