Swift - Custom Type Extending Properties

Introduction

Extensions work with computed properties.

Extensions in Swift do not support stored properties.

Consider the following code

Demo

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

You could extend the Distance class by adding computed properties to it:

extension Distance {
    var feet: Double { return miles * 5280 }
    var yard: Double { return miles * 1760 }
}

In the preceding code snippet, you added two new computed properties to the Distance class:

  • feet - To convert the miles to feet
  • yard - To convert the miles to yards

You can use the newly added computed properties as shown here:

Demo

class Distance {
     var miles = 0.0
     var km: Double {
         get {//w  ww  . j  ava 2s .co  m
             return 1.60934 * miles
         }
         set (km) {
             miles = km / 1.60934
         }
     }
}

extension Distance {
    var feet: Double { return miles * 5280 }
    var yard: Double { return miles * 1760 }
}

var d = Distance ()
d.miles = 10
print(d.feet)   //52800.0
print(d.yard)   //17600.0

Result

Related Topic