1

我有这个结构:

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

let alphabet = Alphabet()

我希望每个属性的值成为属性本身的字符串。像这样:

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

但无论属性的数量或其价值如何,我都想完成:

我试过这个:

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

但我知道这不是 KeyPath 的工作方式......可能也存在类型安全问题。任何想法?

4

1 回答 1

1

据我所知 keyPaths 不是要走的路,你需要使用 CodingKeys

这是一个工作示例,创建 JSON 然后对其进行解码可能不是完美的,因此您最好更改我的解决方案以满足您的需求。



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"

于 2020-01-07T16:02:25.090 回答