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版本中给我们带来更大的便利。