Why doesn't Int64 automatically conform to CodingKeyRepresentable?

I came here originally to ask why Int64 can't be used as a JSON dictionary key by JsonEncoder even though Int can. I discovered various posts about this, and ultimately that types besides Int and String can be used as dictionary keys as of SE-0320 in Swift 5.6. I was able to add CodingKeyRepresentable to Int64 myself by serializing it to a string and back, and it seems to work great.

struct MyCodingKey: CodingKey {
    let stringValue: String
    let intValue: Int?
    
    init(stringValue: String) {
        self.stringValue = stringValue
        self.intValue = Int(stringValue)
    }
    
    init(intValue: Int) {
        self.stringValue = "\(intValue)"
        self.intValue = intValue
    }
}

extension Int64 : CodingKeyRepresentable {
    public var codingKey: CodingKey {
        MyCodingKey(stringValue: "\(self)")
      }
      public init?<T: CodingKey>(codingKey: T) {
          if let intValue = Int64(codingKey.stringValue) {
          self = intValue
        } else {
          return nil
        }
      }
}

I still wonder, though: why isn't CodingKeyRepresentable conformance built-in on Int64?

1 Like

I found the answer here:

And as to why Int64 wasn't originally supported as a key: it's tricky to read back out.

Hopefully this question makes that more discoverable by search.

2 Likes