Walter M
Walter M

Reputation: 5533

Need clarification on using dot-notation on literals in Swift

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.

Upvotes: 0

Views: 407

Answers (1)

Patrick Lynch
Patrick Lynch

Reputation: 2782

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

Upvotes: 3

Related Questions