获取 Swift 中键路径的编码密钥

Nic*_*gen 1 swift codable swift-keypath

我拥有的:具有不同属性的可编码结构。

我想要的:一个函数,当属性编码为 Json 时,我可以在其中获取属性的确切名称。我认为最有前途的方法是使用 Keypath,但我不知道如何以及是否可能。谢谢!

Dáv*_*tor 6

没有办法开箱即用地执行此操作,因为类型的属性Codable与其编码键之间不存在 1-1 映射,因为可能存在不属于编码模型的属性或依赖于多个编码的属性键。

但是,您应该能够通过定义属性及其编码键之间的映射来实现您的目标。您在 s 方面走在正确的轨道上KeyPath,您只需要定义一个函数,该函数采用的KeyPath根类型是您的可编码模型,并从该函数返回编码密钥。

struct MyCodable: Codable {
    let id: Int
    let name: String

    // This property isn't part of the JSON
    var description: String {
        "\(id) \(name)"
    }

    enum CodingKeys: String, CodingKey {
        case name = "Name"
        case id = "identifier"
    }

    static func codingKey<Value>(for keyPath: KeyPath<MyCodable, Value>) -> String? {
        let codingKey: CodingKeys
        switch keyPath {
        case \MyCodable.id:
            codingKey = .id
        case \MyCodable.name:
            codingKey = .name
        default: // handle properties that aren't encoded
            return nil
        }
        return codingKey.rawValue
    }
}

MyCodable.codingKey(for: \.id)
Run Code Online (Sandbox Code Playgroud)