Created
March 1, 2019 18:40
-
-
Save IanKeen/3d226854c8c59a17e151a0022b71f6bb to your computer and use it in GitHub Desktop.
AnyCodingKey: Helpful for a range of Codable tricks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct AnyCodingKey: CodingKey { | |
var stringValue: String | |
var intValue: Int? | |
init?(intValue: Int) { | |
self.intValue = intValue | |
self.stringValue = "\(intValue)" | |
} | |
init?(stringValue: String) { | |
self.intValue = nil | |
self.stringValue = stringValue | |
} | |
} | |
extension AnyCodingKey { | |
init<T: CodingKey>(_ key: T) { | |
self.stringValue = key.stringValue | |
self.intValue = key.intValue | |
} | |
init(_ int: Int) { | |
self.init(intValue: int)! | |
} | |
init(_ string: String) { | |
self.init(stringValue: string)! | |
} | |
} | |
extension AnyCodingKey: ExpressibleByStringLiteral { | |
init(stringLiteral value: String) { | |
self.init(stringValue: value)! | |
} | |
} | |
extension AnyCodingKey: ExpressibleByIntegerLiteral { | |
init(integerLiteral value: Int) { | |
self.init(intValue: value)! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment