Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created March 1, 2019 18:40
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanKeen/3d226854c8c59a17e151a0022b71f6bb to your computer and use it in GitHub Desktop.
Save IanKeen/3d226854c8c59a17e151a0022b71f6bb to your computer and use it in GitHub Desktop.
AnyCodingKey: Helpful for a range of Codable tricks
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