I am new to Firestore. For example I have an Object like this:
struct Item: Codable {
let key: String?
let value: ItemAnyValueType?
}
public indirect enum ItemAnyValueType: Codable {
case string(String)
case bool(Bool)
public init(from decoder: Decoder) throws {
let singleValueContainer = try decoder.singleValueContainer()
if let value = try? singleValueContainer.decode(Bool.self) {
self = .bool(value)
return
} else if let value = try? singleValueContainer.decode(String.self) {
self = .string(value)
return
}
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Error"))
}
private enum CodingKeys: String, CodingKey {
case string
case bool
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .string(let value):
try container.encode(value, forKey: .string)
case .bool(let value):
try container.encode(value, forKey: .bool)
}
}
}
The item in Firestore looks like this:
documents
id: 123123 -> key: "test1", value: true
id: 323412 -> key: "test2", value: "good"
id: xx2332 -> key: "test3", value: "i love cats"
id: 433xxx -> key: "test4", value: "i love dogs"
The field value can be boolean or string.
Example of the saved data:
...
...
...
.document("433xxx")
.setData(from: Item(key: "433xxx", value: .string("i love orange")),
merge: true,
completion: { (error) in
print("ok")
})
but the code saves like this:
id: 433xxx -> key: "433xxx", value: map {string: "i love orange"}