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

时间:2020-10-12 09:14:35

标签: swift codable swift-keypath

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

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

1 个答案:

答案 0 :(得分:2)

由于Codable类型的属性与其编码键之间没有1-1映射,因此无法立即执行此操作,因为可能存在某些属性不属于已编码取决于几个编码键的模型或属性。

但是,应该可以通过定义属性与其编码键之间的映射来实现目标。您使用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)