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'm having is that Decimal
is a struct, so I have to bridge it to an NSDecimalNumber
every time I want to use a formatter, which I'd like to avoid.
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let decimal = Decimal(integerLiteral: 3)
let string = formatter.string(from: decimal as NSDecimalNumber)
Is the ideal workaround for this to implement my own extension that takes a Decimal
?
extension NumberFormatter {
open func string(from number: Decimal) -> String? {
return string(from: number as NSDecimalNumber)
}
}
More generally, every time I need to pass in an object type am I going to need to bridge Decimal
or write more extensions?
EDIT
I guess I'm wondering more generally about NSDecimal
Decimal
and NSDecimalNumber
in Swift 3. It's not clear to me at all what's going on here. Should I be replacing NSDecimalNumber
with Decimal
for Swift 3? The docs write:
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.
Which at first I thought meant that Decimal
was the new NSDecimalNumber
like Error
is the new NSError
- but now I'm not so sure. That also says 'Decimal value type offers the same functionality as the NSDecimalNumber reference type` - is this really true? I can't seem to get much of the same functionality (without bridging it first, of course, is that what they mean?). I have found a few posts and a bit of info here and there, but nothing that convincing. Does anyone have any knowledge or insight?
My app specifically is using NSDecimalNumber
for currency and formatting, so rounding and formatting are a high priority.