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版本中給我們帶來更大的便利。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章