Firestore. Swift. Create document with dynamic field

I am new in 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)
        }
    }
}

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 for save data:

...
...
...
 .document("433xxx")
                .setData(from: Item(key: "433xxx", value: .string("i love orange")),
                         merge: true,
                         completion: { (error) in
                            print("ok")
                         })

but it code will save like this:

id: 433xxx -> key: "433xxx", value: map {string: "i love orange"}


Read more here: https://stackoverflow.com/questions/68459806/firestore-swift-create-document-with-dynamic-field

Content Attribution

This content was originally published by yaxise5555 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: