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.
You are supposed to use
as
operator to cast a Swift type to its bridged underlying Objective-C type. So just useas
like this.In Swift 4,
Decimal
isNSDecimalNumber
. Here's citation from Apple's official documentation in Xcode 10.There's no
NSDecimal
anymore. There was confusingNSDecimal
type in Swift 3, but it seems to be a bug. No more confusion.Note
I see the OP is not interested in Swift 4, but I added this answer because mentioning only about (outdated) Swift 3 made me confused.
Decimal
in Swift 3 is notNSDecimalNumber
. It'sNSDecimal
, completely different type.You should just keep using
NSDecimalNumber
as you did before.Solution that works in Swift 4
Edit: Without
NSDecimalNumber
/NSNumber
Another solution that works in Swift 3 is to cast the
Decimal
toNSNumber
and create theDouble
from that.NSDecimalNumber
andDecimal
are bridgedbut as with some other bridged types certain elements are missing.
To regain the functionality you could write an extension: