问题描述
是否可以扩展 NSDecimalNumber
以符合 Encodable &可解码
协议?
Is it possible to extend NSDecimalNumber
to conform Encodable & Decodable
protocols?
推荐答案
无法扩展 NSDecimalNumber
以符合 Encodable
&可解码
协议.Jordan Rose 在以下 swift 进化电子邮件线程 中对此进行了解释.
It is not possible to extend NSDecimalNumber
to conform to Encodable
& Decodable
protocols. Jordan Rose explains it in the following swift evolution email thread.
如果您需要在 API 中输入 NSDecimalValue
类型,您可以围绕 Decimal
构建计算属性.
If you need NSDecimalValue
type in your API you can build computed property around Decimal
.
struct YourType: Codable {
var decimalNumber: NSDecimalNumber {
get { return NSDecimalNumber(decimal: decimalValue) }
set { decimalValue = newValue.decimalValue }
}
private var decimalValue: Decimal
}
顺便说一句.如果您使用 NSNumberFormatter
进行解析,请注意 已知错误 在某些情况下会导致精度损失.
Btw. If you are using NSNumberFormatter
for parsing, beware of a known bug that causes precision loss in some cases.
let f = NumberFormatter()
f.generatesDecimalNumbers = true
f.locale = Locale(identifier: "en_US_POSIX")
let z = f.number(from: "8.3")!
// z.decimalValue._exponent is not -1
// z.decimalValue._mantissa is not (83, 0, 0, 0, 0, 0, 0, 0)
以这种方式解析字符串:
Parse strings this way instead:
NSDecimalNumber(string: "8.3", locale: Locale(identifier: "en_US_POSIX"))
这篇关于使 NSDecimalNumber 可编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!