2017-09-19 7 views
2

NSDecimalNumberEncodable & Decodableプロトコルに準拠させることは可能ですか?NSDecimalNumberをコーディング可能にする

+0

?あなたの要件は何ですか?何をエンコード/デコードしようとしていますか? –

+0

@LorenzoBカスタムタイプのエンコードとデコードについては、アップルのドキュメントhttps://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_typesをチェックしました。私はDoubleを使用した場合、私が精度が低いサーバーからの応答を解析しようとしています。 –

答えて

1

すぐにDecimalタイプを使用してください。このタイプは、プロトコルEncodable & Decodableをボックスから確認します。

あなたのコードでNSDecimalNumberタイプを持っている場合は、それはEncodable & Decodableプロトコルに準拠するようにNSDecimalNumberを拡張することはできませんDecimal

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

にキャストするのは簡単です。ジョーダンローズは次のように説明します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")) 
関連する問題