0

So I am reading about Class Extensions in the Swift documentation. I understand the purpose and functionality of a class extensions. Then, Apple provides this example of how to extend an existing type:

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"

Can someone explain why and how it's possible to use dot notation on a floating-point literal?

In the example above they use the dot notation on the values 25.4 and 3 to access computed properties of the Double class. Apple does not give thorough explanation on why this can be done.

Walter M
  • 4,993
  • 5
  • 22
  • 29

1 Answers1

3

This is made possible by Swift's literal convertibles:

http://nshipster.com/swift-literal-convertible/

As the great Matt Thompson notes near the bottom of that article:

One neat feature of literal convertibles is that the type inference works even without a variable declaration:

"http://nshipster.com/".host // nshipster.com

Patrick Lynch
  • 2,742
  • 1
  • 16
  • 18
  • Woaw! Thank you for this! Why is this not in the Swift documentation?? lol. Anyways, thank you for answering my question. By the way, what additional swift documentation do you recommend. It now seems I won't be able to learn everything about swift if I just use Apple's own documentation. – Walter M Aug 07 '15 at 00:11
  • There are some real smart people out there with blogs and books: [NS Hipster](http://www.nshipster.com), [Practical Swift](http://www.practicalswift.com), and [Air Speed Velocity](http://www.airspeedvelocity.net) are my favorites. – Patrick Lynch Aug 07 '15 at 00:24
  • @WalterM Eh, I don't think it's something worth mentioning, particularly early on. The fact that a double is a double is a double is not surprising. To the contrary, that fact that other languages don't support methods and such on their doubles, whether on their literal representation or otherwise, *that's* surprising. There's no reason for that arbitrary limitation – Alexander Sep 18 '19 at 03:49