首页 > 解决方案 > RealmSwift and Codable when using optional types

问题描述

I've been using RealmSwift and Codable for a long time in a project, however, my api dev just gave me two new properties that only exist on some return calls of an object. If I call getUserInfo, I receive a user model without these two properties. In such an instance, you would use decodeIfPresent in codable and set the data type to optional. However, these two fields are epoch time values, making them some sort of number. Realm requires your datatypes to be prefixed with @objc.

@objc dynamic var scanIn:Double = 0

Of course, all number primitives work like this, but NONE of them work as optionals. You must use NSNumber or similar to use optionals with ObjC, but lucky me, Codable doesn't work with NSNumber. I know I have a lot of different options here, but I was really looking for something simple and quick that wouldn't require me to rebuild the entire model with mapping or convert everything when I receive it. I'll be writing that out a workaround for now, but I would really like to keep things simple and clean.

I tried setting a value if none return and just using a non-optional type like this

scanIn = try container.decodeIfPresent(Double.self, forKey:.scanIn) ?? 0

However, this sets ALL values to 0 for some reason. I have no idea why it does that, but another dev has advised that it doesn't work in codable like that and I had to set the double to optional. I would like to clarify that this number exists immediately before conversion, but is 0 after.

Any ideas on an easy fix? Maybe I'm doing something wrong?

标签: swiftswift3realmcodable

解决方案


你可以使用RealmOptional<Double>类型。

文档中所述:

可选数字类型使用以下RealmOptional类型声明:

let age = RealmOptional<Int>()

RealmOptional支持Int, Float, Double, , 和( , , , )Bool的所有大小版本。IntInt8Int16Int32Int64


推荐阅读