Skip to content

Instantly share code, notes, and snippets.

@hartbit
Last active February 18, 2018 18:39
Show Gist options
  • Save hartbit/b9fec8535afdf4e40920a1134a919b2c to your computer and use it in GitHub Desktop.
Save hartbit/b9fec8535afdf4e40920a1134a919b2c to your computer and use it in GitHub Desktop.

Given a protocol that refines CodingKey:

protocol DocumentedCodingKey: CodingKey {
    var documentation: String { get }
}

I'd like to be able to conform the automatically generated CodingKeys to it:

struct Foo: Codable {
    let a: String
    let b: Int?
    let c: Bool
    let d: Date?
}

extension Foo.CodingKeys: DocumentedCodingKey {
    var documentation: String {
        switch self {
        case .a: return "This is an a"
        case .b: return "This is a b"
        case .c: return "This is a c"
        case .d: return "This is a d"
        }
    }
}

but I can't because CodingKeys is defined as private, which forces me to explicitly define it even when I'm not customizing its cases, which is not very DRY:

struct Foo: Codable {
    enum CodingKeys: DocumentedCodingKey {
        case a
        case b
        case c
        case d

        var documentation: String {
            switch self {
            case .a: return "This is an a"
            case .b: return "This is a b"
            case .c: return "This is a c"
            case .d: return "This is a d"
            }
        }
    }

    let a: String
    let b: Int?
    let c: Bool
    let d: Date?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment