在玩家模型中,我想保存 JSON 响应,以便将来在不更改架构的情况下获得任何新的计算属性。
但是在这里,我在保存 [String: Any] 类型的 json 时遇到错误。
有什么替代方案或建议...?
Any
不是 Map 支持的值类型。查看 Map 的文档,其中显示了定义
public final class Map<Key, Value>
value是一个RealmCollectionValue可以是以下类型之一
这可以是对象子类或以下类型之一: 布尔、Int、Int8、Int16、Int32、Int64、浮点、双精度、字符串、数据、 Date、Decimal128 和 ObjectId(及其可选版本)
一种选择是使用 AnyRealmValue 所以它看起来像这样
class Player: Object {
@Persisted var json = Map<String, AnyRealmValue>()
}
这是如何使用字符串和 int 填充 json
let s: AnyRealmValue = .string("Hello")
let i: AnyRealmValue = .int(100)
let p = Player()
p.json["key 0"] = s
p.json["key 1"] = i
然后取回存储在地图中的值:
for key in p.json {
let v = key.value
if let s = v.stringValue {
print("it's a string: \(s)")
} else if let i = v.intValue {
print("it's an int: \(i)")
}
}
和输出
it's a string: Hello
it's an int: 100