The Problem with Extensions

The extensions feature in Swift has many use cases. You can read them all in more detail in their documentation. Here we’ll just deal with the general case and the protocol case.

Following the example in Apple documentation:

 extension Double {
  var km: Double { return self * 1_000.0 }
  var m: Double { return self }
  var cm: Double { return self / 100.0 }
  var mm: Double { return self / 1_000.0 }
  var ft: Double { return self / 3.28084 }
 }
 let oneInch = 25.4.mm
 println("One inch is \(oneInch) meters")
 // prints "One inch is 0.0254 meters"
 
 let threeFeet = 3.ft
 println("Three feet is \(threeFeet) meters")
 // prints "Three feet is 0.914399970739201 meters"

In this example, we are extending the Double ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.