Decimal to Double conversion in Swift 3

Zaphod picture Zaphod · Oct 6, 2016 · Viewed 41k times · Source

I'm migrating a project from Swift 2.2 to Swift 3, and I'm trying to get rid of old Cocoa data types when possible.

My problem is here: migrating NSDecimalNumber to Decimal.

I used to bridge NSDecimalNumber to Double both ways in Swift 2.2:

let double = 3.14
let decimalNumber = NSDecimalNumber(value: double)

let doubleFromDecimal = decimalNumber.doubleValue

Now, switching to Swift 3:

let double = 3.14
let decimal = Decimal(double)

let doubleFromDecimal = ???

decimal.doubleValue does not exist, nor Double(decimal), not even decimal as Double... The only hack I come up with is:

let doubleFromDecimal = (decimal as NSDecimalNumber).doubleValue

But that would be completely stupid to try to get rid of NSDecimalNumber, and have to use it once in a while...

Well, either I missed something obvious, and I beg your pardon for wasting your time, or there's a loophole needed to be addressed, in my opinion...

Thanks in advance for your help.

Edit : Nothing more on the subject on Swift 4.

Edit : Nothing more on the subject on Swift 5.

Answer

sketchyTech picture sketchyTech · Oct 6, 2016

NSDecimalNumber and Decimal are bridged

The Swift overlay to the Foundation framework provides the Decimal structure, which bridges to the NSDecimalNumber class. The Decimal value type offers the same functionality as the NSDecimalNumber reference type, and the two can be used interchangeably in Swift code that interacts with Objective-C APIs. This behavior is similar to how Swift bridges standard string, numeric, and collection types to their corresponding Foundation classes. Apple Docs

but as with some other bridged types certain elements are missing.

To regain the functionality you could write an extension:

extension Decimal {
    var doubleValue:Double {
        return NSDecimalNumber(decimal:self).doubleValue
    }
}

// implementation
let d = Decimal(floatLiteral: 10.65)
d.doubleValue