Suppose I have the following struct definition and dictionary:
struct Point: Codable {
let x: Int
let y: Int
}
let pointDictionary = [ "x": 0, "y": 1]
// Inital example was too easy so also we might have
struct Score: Codable {
let points: Int
let name: String
}
let scoreDictionary: [String: Any] = [
"points": 10,
"name": "iOSDevZone"
]
Is there a way, without a roundtrip through JSON or PList, to populate an instance of the struct Point
from pointDictionary
?
What I've Tried
I've looked at the Apple docs and can't really find a way.
To be clear, I understand I could write a custom initializer that takes a Dictionary (as I was submitting this question the system matched with an answer that illustrates this), but that's not what I am asking. (And this is not practical in my real situation, this is purely a demonstrative example).
I am asking, given a [String:Any]
Dictionary where the keys match the property names of a struct and the values are convertible to the types of the properties, is there a way of leveraging Decodable
to initialize the struct?
Why a Dictionary init is not desirable Since most responses have been: "Why not implement a dictionary init?"
There are lots of structs and many properties, the dictionaries come from processing bad JSON (that I have no control over).