While it's not recommended you conform types you don't own to protocols you don't own, until Int64
adopts CodingKeyRepresentable
, you could implement a conformance as follows:
// Need a key type which can hold any Int value.
struct IntCodingKey: CodingKey {
let intValue: Int?
let stringValue: String
init(intValue: Int) {
self.intValue = intValue
self.stringValue = String(describing: intValue)
}
init?(stringValue: String) {
guard let intValue = Int(stringValue) else { return nil }
self.intValue = intValue
self.stringValue = stringValue
}
}
extension Int64: CodingKeyRepresentable {
public var codingKey: CodingKey {
guard let intValue = Int(exactly: self) else {
// Figure out how to handle this!!
}
return IntCodingKey(intValue: intValue)
}
public init?<T: CodingKey>(codingKey: T) {
guard let intValue = codingKey.intValue ?? Int(codingKey.stringValue) else {
return nil
}
self.init(exactly: intValue)
}
}
Importantly, you'll need to figure out how to handle converting an Int64
into an Int
if you're targeting 32-bit platforms, since a 64-bit Int64
can't necessarily fit into a 32-bit Int
. If you can guarantee that you'll only ever target 64-bit platforms or larger, then you won't really need to worry about this (and potentially, a fatalError
would suffice), but I suspect that the Swift stdlib wouldn't want to implement it that way itself. (Though I could imagine adding conditionally Int64: CodingKeyRepresentable
to the stdlib based on target architecture — maybe Int64
isn't CodingKeyRepresentable
on 32-bit systems.)