0

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!

1 Answer 1

1

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] ?? [:]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.