映射swift时写变量的setter和getter方法?

时间:2018-02-05 03:28:52

标签: json swift mapping

我想在映射时修改roomTotal键的值。请参考以下代码:

struct TransactionInfoModel: Codable {
   var currencyCode: String
   var total: Double
   var roomCurrencyCode: String
   var exchangeRate: Double

   var roomTotal: Double {
      get {
        let y = (self.roomTotal*100).rounded()/100
        return y
      }
   }
}

最初,roomTotal键具有来自服务器的值,如“427.3000000002”但我希望在映射时存储值“427.3”。上面的代码不起作用。

寻找解决此问题的一些建议。

1 个答案:

答案 0 :(得分:1)

请参阅this answer,了解如何舍入Double值并返回保留舍入的Decimal值,而不会在尝试表示十进制值时产生任何工件二进制浮点表示。然后,您可以像这样获得舍入的Decimal值:

let roomTotal = 427.3000000002
let value = roomTotal.roundedDecimal(to: 2)

如果你想用指定的小数位数显示它(以及为用户的当前语言环境本地化字符串),你可以使用NumberFormatter

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2

if let string = formatter.string(for: value) {
    print(string)
}

现在,如果您希望JSONDecoder为您执行此转换,您可以,但我可能倾向于让struct准确地代表返回的内容,避免任何错综复杂的{{1}实现,但可能包含一个计算属性,以您想要的格式返回值,例如:

init(from:)

如果您在解码时需要对struct TransactionInfoModel: Codable { var currencyCode: String var total: Double var roomCurrencyCode: String var exchangeRate: Double var roomTotal: Double var roundedRoomTotal: Decimal { return roomTotal.roundedDecimal(to: 2) } } 进行舍入,可以编写roomTotal来执行此操作:

init(from:)

或者,您可以省略struct TransactionInfoModel: Codable { var currencyCode: String var total: Double var roomCurrencyCode: String var exchangeRate: Double var roomTotal: Decimal init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) currencyCode = try values.decode(String.self, forKey: .currencyCode) total = try values.decode(Double.self, forKey: .total) roomCurrencyCode = try values.decode(String.self, forKey: .roomCurrencyCode) exchangeRate = try values.decode(Double.self, forKey: .exchangeRate) roomTotal = try values.decode(Double.self, forKey: .roomTotal).roundedDecimal(to: 2) } } ,但在解析后手动将其舍入:

init(from:)

struct TransactionInfoModel: Codable {
    var currencyCode: String
    var total: Double
    var roomCurrencyCode: String
    var exchangeRate: Double
    var roomTotal: Decimal
}