Preface
Swift 4 is the latest version Apple plans to launch in fall 2017, with its main focus on providing source compatibility with Swift 3 code and working to achieve ABI stability. Decodable parsing JSON from Swift4 is indeed very convenient, but when you encounter a small problem, please record it.
When the value of a key in JSON is {} or an empty string "" and the value that needs to be parsed is not the basic type, even if it is marked as Optional, the entire parsing will still fail:
//: Playground import Foundation // struct Book: Codable { var id: Int var name: String var cover: BookCover? enum CodingKeys: String, CodingKey { case id case name case cover } struct BookCover: Codable { var url: String var thumbURL: String enum CodingKeys: String, CodingKey { case url case thumbURL = "thumb_url" } } } //JSON let bookJSON1 = """ { "id": 1, "name": "fake name 1", "cover": { "url": "", "thumb_url": "" } } """ let bookJSON2 = """ { "id": 2, "name": "fake name 2", "cover": { } } """ //Analysislet decoder = JSONDecoder() = .iso8601 let book1 = try? (, from: (using: .utf8)!) // The parsing is normalprint(book1) let book2 = try? (, from: (using: .utf8)!) // Output nil, cover is already Optional, why does the entire book fail to parse?print(book2)
reason:
Because cover is Optional, decodeIfPresent will be called for parsing, and the two keys of url and thumb_url are not found in the cover node, resulting in the default resolution failure and an error is directly thrown.
solve:
Reimplement decodeIfPresent, returning nil when parsing fails instead of throwing an error causing the entire parsing to fail:
extension KeyedDecodingContainer { public func decodeIfPresent<T>(_ type: , forKey key: K) throws -> T? where T : Decodable { return try? decode(type, forKey: key) } }
refer to:/2017/08/16/jsondecoder-in-the-real-world
Summarize
The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.