记录一个iOS9~10 Int64解析的系统问题

253 阅读1分钟

问题背景:后端基于雪花算法生成19位随机数的id,Codable的Int64接收id之后,在iOS10上运行抛出错误:

▿ DecodingError
  ▿ dataCorrupted : Context
    ▿ codingPath : 3 elements
      - 0 : CodingKeys(stringValue: "list", intValue: nil)
      ▿ 1 : _JSONKey(stringValue: "Index 5", intValue: 5)
        - stringValue : "Index 5"
        ▿ intValue : Optional<Int>
          - some : 5
      - 2 : CodingKeys(stringValue: "id", intValue: nil)
    - debugDescription : "Parsed JSON number <1517213741861863230> does not fit in Int64."
    - underlyingError : nil

聊一聊解决方案 1、数据溢出了,改用String类型,简单粗暴(要跟后端PK,说服不了他们就往下看看。。)

2、Int64不行的话,考虑下Double咯 为KeyedDecodingContainer重写下

func decodeIfPresent(_ type: Int64.Type, forKey key: K) throws -> Int64? {
        guard try contains(key) && !decodeNil(forKey: key) else { return nil }
        let decoder = try superDecoder(forKey: key)
        let container = try decoder.singleValueContainer()
        if let value = try? container.decode(type) {
            return value
        } else if let stringValue = try? container.decode(String.self) {
            if let intValue = Int64(stringValue) {
                return intValue
            } else if let doubleValue = Double(stringValue) {
                return Int64(doubleValue)
            }
            else {
                return nil
            }
        } else if #available(iOS 11.0, *), let doubleValue = try? container.decode(Double.self) {
            return Int64(doubleValue)
        }
        return nil
    }

时间仓促,有空再码 用于测试demo(方案来自同事henry哥)

github.com/wengcanzi/I…