I am trying to use NumberFormatter
with Swift 3 Decimal
, but I\'m confused as to how Decimal
is really being implemented. The problem
I asked my question on the swift-users board and got a wonderful answer, check it out here: https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20161219/004220.html
Text version of the response:
Swift 3 introduced the Decimal class, which at first I thought was supposed to 'replace' NSDecimalNumber in Swift, like Error is the new NSError, etc. However, upon further investigation, it's not clear to me that this is actually the case. It appears that Swift 3's Decimal is more just an NSDecimal, but with some bridging so it can use NSDecimalNumber's methods when needed. What I'm wondering is, should I be replacing NSDecimalNumber in my app with Decimal? Is Decimal the successor to NSDecimalNumber in Swift?
Decimal
is actually a struct, not a class, and in fact it's just the Swift name for the NSDecimal
struct in Objective-C. In Swift, functions like NSDecimalAdd
are exposed as operators on Decimal
and are used to satisfy the requirements of various numeric protocols like SignedNumber
.
The end result is that Decimal
is a lot like Int
or Double
—it's a value type which can be conveniently used to do all sorts of math. NSDecimalNumber
, then, is equivalent to NSNumber
.
Since my app is doing a lot of formatting, it would require much casting between Decimal and NSDecimalNumber, or adding of extensions to use, so I don't think it would be natural/convenient without many extensions. Is Swift planning to improve Decimal to be more usable with NumberFormatter, or other object-oriented number APIs? Hopefully I have given enough information to answer my question.
Objective-C APIs which use NSDecimalNumber
should be bridged to Decimal
, just as NSString
is bridged to String
. That bridging may not work for category methods, though; you could expose those to Swift by writing an extension on Decimal
which casts self
to NSDecimalNumber
and then calls through to your Objective-C methods.
Similarly, you should be able to use Decimal
with NumberFormatter
by casting to NSDecimalNumber
, just as you would cast Int
or Double
to NSNumber
to use them with NumberFormatter
.