如何在Swift 4 Codable中存储Big Integer?

问题描述 投票:-1回答:2

我正在尝试使用swift 4可编码自动解析API。 API中的一些字段是Codable不支持的大整数,也不是Codable不支持Swift 4.NSNumber,而且UInt64很小。我尝试了一个第三方库并将我的变量放在可编码的那个类型中,但这也没有用。我试图创建一个自定义类或结构,它只使用容器中的一个值进行转换,但不知道如何使容器接受Big Int类型或将其转换为字符串。我的代码就像这样。有什么解决方案吗?

import Foundation
import BigNumber

class PersonalizationLean:Codable {

    var hubId:String?
    var appId:UInt8?
    var nodeId:Int?
    var name:String?
    var ico:String?
    var icoBase64:String?
    var isBin:Bool?
    var lastModifiedAt:Int?
    var shouldShowInUi:Bool?
    var applianceType:String?
    var tags:[String]?
    var placeId:PlaceIdCodable?
    var roomId:String?
    var id:String?
    var key:String?


    enum CodingKeys:String,CodingKey {
        case hubId
        case appId
        case nodeId
        case name
        case ico
        case icoBase64
        case isBin
        case lastModifiedAt
        case shouldShowInUi
        case applianceType
        case tags
        case placeId
        case roomId
        case id
        case key
    }

//    required init(from decoder: Decoder) throws {
//        do {
//            let container = try decoder.container(keyedBy: CodingKeys.self)
//            self.hubId = try container.decode(String.self, forKey: .hubId)
//            self.appId = try container.decode(UInt8.self, forKey: .appId)
//            self.nodeId = try container.decode(Int.self, forKey: .nodeId)
//            self.name = try container.decode(String.self, forKey: .name)
//            self.ico = try container.decode(String.self, forKey: .ico)
//            self.icoBase64 = try container.decode(String.self, forKey: .icoBase64)
//            self.isBin = try container.decode(Bool.self, forKey: .isBin)
//            self.lastModifiedAt = try container.decode(Int.self, forKey: .lastModifiedAt)
//            self.shouldShowInUi = try container.decode(Bool.self, forKey: .shouldShowInUi)
//            self.applianceType = try container.decode(String.self,forKey: .applianceType)
//            self.tags = try container.decode([String].self,forKey: .tags)
//
//
//        }catch {
//            print(error)
//        }
//    }

}

class PlaceIdCodable:Codable {
    var placeId:String?

    required init(from decoder:Decoder) throws {
        do  {
            let container = try decoder.singleValueContainer()
            let placeIdBig = try container.decode(BInt.self) //this gives error
        }catch {
            print(error)
        }

    }

}

我使用的图书馆是BigNumber

ios swift swift4 biginteger codable
2个回答
1
投票

使用源自Decimal的内置NSDecimalNumber。它采用Codable


0
投票

BInt不符合CodableDecodable

在这里使用它应该确认提到的协议

extension BInt: Decodable {
    public init(from decoder: Decoder) throws {
        // Initialization goes here
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.