Home > Software design >  Create a dictionary from a Codable struct with all CodingKeys and values
Create a dictionary from a Codable struct with all CodingKeys and values

Time:12-14

Is it possible to associate the stored values of properties in a Codable struct with the CodingKeys of said properties, and return them without manual configuration of each struct?

I am trying to achieve the following:

struct MyStruct: Codable {
    
    let propertyOne: String = "Value One"
    let propertyTwo: String = "Value Two"
    
    enum CodingKeys: String, CodingKey {
        case propertyOne = "Coding Key One"
        case propertyTwo = "Coding Key Two"
    }
    
    func allValues() -> [String: String] {

    /*
     
     return something like: [
        "Coding Key One": "Value One",
        "Coding Key Two": "Value Two"
     ]
     
     */

    }
}

Using Mirror() doesn't help much because it returns a label which is the property's name as a String, but I require the CodingKey. And CaseIterable doesn't get the values of the stored properties.

Thank you in advance!

CodePudding user response:

You could use JSONSerialization to get your dictionary

func allValues() throws -> [String: String] {
    let data = try JSONEncoder().encode(self)
    return try JSONSerialization.jsonObject(with: data) as? [String: String] ?? [:]
}
  • Related