Swfit4中Codable解析"Any"类型的问题(Type 'XX' does not conform to protocol 'Decodable')

0x01 问题

因为Swift4中引入了新协议"Codable",所以我想在最近的项目中不使用第三方库来解析,而使用原生的特性来处理。在写下面这么一个entity的时候,提示“Type 'Block' does not conform to protocol 'Decodable'”:

struct Block: Codable {
    let message: String
    let index: Int
    let transactions: [[String: Any]]
    let proof: String
    let previous_hash: String
}

 

0x02 过程

 

借助stackoverflow上的一个问题的回答:

You cannot currently decode a [String: Any] with the Swift coding framework...

...

There has been discussion of this issue on Swift Evolution: “Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4”. Apple's main Coding/Codable programmer, Itai Ferber, has been involved in the discussion and is interested in providing a solution, but it is unlikely to happen for Swift 5 (which will probably be announced at WWDC 2018 and finalized around September/October 2018).

这一块苹果现在应该是没有对应的直接解析的方案了。

然后我们再看一下苹果的文档,实际上已经有自己的解决方式了,如下:

struct Coordinate: Codable {
    var latitude: Double
    var longitude: Double
}

struct Landmark: Codable {
    // Double, String, and Int all conform to Codable.
    var name: String
    var foundingYear: Int
    
    // Adding a property of a custom Codable type maintains overall Codable conformance.
    var location: Coordinate
}

 

和其他第三方库类似,对非原生类型字段,给它再生成一个struct,用原生类型来表述属性就行了。

 

所以,我们再新建一个struct Transaction就OK了:

struct Transaction: Codable {
    let amount: Int
    let recipient: String
    let sender: String
}

struct Block: Codable {
    let message: String
    let index: Int
    let transactions: [Transaction]
    let proof: String
    let previous_hash: String
}

 

 

0x03 结论

 

 

相信苹果能在后面Swift版本中给我们带来更大的便利。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值