O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required