Swift - When to use Computed Properties

Introduction

Consider another example:

class Distance {
    var miles = 0.0
    var km: Double {
        get {
            return 1.60934 * miles
        }
        set (km) {
            miles = km / 1.60934
        }
    }
}

Here, you have the Distance class.

It has a stored property named miles.

You have a km computed property.

The km computed property enables you to retrieve the distance in kilometers:

Demo

class Distance {
    var miles = 0.0
    var km: Double {
        get {//from   ww  w. j  a v a 2 s . c  o  m
            return 1.60934 * miles
        }
        set (km) {
            miles = km / 1.60934
        }
    }
}

var d = Distance ()
d.miles  = 10.0
print(d.km)     //16.0934

Result

It also enables you to store a distance in kilometers:

d.km = 20.0
print(d.miles)  //12.4274547329961

Here, the actual distance is stored in miles, not kilometers.

That way, you only need to store the distance once.

To support yards, you just need to add the computed property as shown here:

class Distance {
    var miles = 0.0
    var km: Double {
        get {
            return 1.60934 * miles
        }
        set (km) {
            miles = km / 1.60934
        }
    }
     var yard:Double {
         get{
             return miles * 1760
         }
         set (yard) {
             miles = yard / 1760
         }
     }
}
var d = Distance ()
d.miles  = 10.0
print(d.km)     //16.0934


d.miles = 1.0
print(d.yard)   //1760.0

d.yard = 234567
print(d.miles)  //133.276704545455

Related Topic