2017-09-19 15 views
2

是否有可能延长NSDecimalNumber符合Encodable & Decodable协议?制作NSDecimalNumber可编码

+0

你尝试过这么远吗?你有什么要求?你想要编码/解码什么? –

+0

@LorenzoB我检查Apple的文档https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types编码和解码的自定义类型。我试图解析来自服务器的响应,如果我使用Double,我会失去精度。 –

回答

1

在急速的,你应该使用Decimal型。该类型从框中确认为协议Encodable & Decodable

如果你在你的代码NSDecimalNumber类型可以很容易地将它转换为Decimal

let objcDecimal = NSDecimalNumber(decimal: 10) 
let swiftDecimal = (objcDecimal as Decimal) 
3

这是不可能延长NSDecimalNumber符合Encodable & Decodable协议。乔丹罗斯在下面的swift evolution email thread中解释它。

如果你需要你的API中NSDecimalValue类型,你可以围绕Decimal建立计算性能。

struct YourType: Codable { 
    var decimalNumber: NSDecimalNumber { 
     get { return NSDecimalNumber(decimal: decimalValue) } 
     set { decimalValue = newValue.decimalValue } 
    } 
    private var decimalValue: Decimal 
} 

Btw。如果你正在使用NSNumberFormatter用于解析,谨防known bug导致在某些情况下,精度的损失。

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) 

解析字符串这种方式来代替:

NSDecimalNumber(string: "8.3", locale: Locale(identifier: "en_US_POSIX"))