Lorenzo Fiamingo
Lorenzo Fiamingo

Reputation: 4109

Assign dynamically properties of a Struct in Swift

I have this Struct:

struct Alphabet {
    let a = "ciao"
    let b = "hi"
    let c = "hola"
}

let alphabet = Alphabet()

I want the value of each property become the string of the property itself. Like this:

alphabet.a = "a"
alphabet.b = "b"
alphabet.c = "c"

But I want to be done regardless of the number of properties or their value:

I tried this:

Mirror(reflecting: Alphabet.self).children.forEach { (label, value) in
    self.alphabet[keyPath: label] = label!
}

but I know this is not the way KeyPath works... Probably there are type safety problems going on too. Any idea?

Upvotes: 2

Views: 1483

Answers (1)

Don
Don

Reputation: 488

As far as I know keyPaths aren't the way to go, you need to use CodingKeys

Here's a working sample, creating JSON and then decoding it might not be the perfect so you better change my solution to suit your needs.



struct Alphabet: Codable {
    let a: String
    let b: String
    let c: String
    enum CodingKeys: String, CodingKey, CaseIterable
    {
        case a
        case b
        case c
    }

    static func generateJSON() -> String {
        var json = "{"
        for i in CodingKeys.allCases
        {
            json += "\"\(i.stringValue)\": \"\(i.stringValue)\","
        }
        json.removeLast()
        json += "}"
        return json
    }
}

let decoder = JSONDecoder()
let alphabet = try decoder.decode(Alphabet.self, from: Alphabet.generateJSON().data(using: .utf8)!)
print(alphabet.a) //Prints "a"

Upvotes: 2

Related Questions