swift - 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?
解决方案
你可以使用RealmOptional<Double>
类型。
如文档中所述:
可选数字类型使用以下
RealmOptional
类型声明:
let age = RealmOptional<Int>()
RealmOptional
支持Int
,Float
,Double
, , 和( , , , )Bool
的所有大小版本。Int
Int8
Int16
Int32
Int64
推荐阅读
- android - Android home screen widget, create from activity
- linux - 无法在 ubuntu 中安装 nvm
- python - 即使我安装了 Python 导入也无法正常工作
- javascript - 使用纯 javascript 的手风琴 - 仅适用于双击
- java - 我们可以在 if 语句中从一个字符串中取出两个字符串吗?
- javascript - 如何添加 CheckAll 按钮
- php - 我的 PHP 云存储平台的数字存储转换如何?还有什么我应该补充的吗?
- python - Python - 如何在每个第 n 个字符后将“*”插入字符串
- angular - 将页面链接到 Angular 8 中页面的各个部分
- python - IndexError:列表索引超出范围..尽管在范围内?