Created
November 30, 2018 03:53
-
-
Save Arcovv/f184600c8443822a4f3a36c500b7c58d to your computer and use it in GitHub Desktop.
Test `decodeIfPresent(_:forKey:)`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let bothValues = """ | |
{ | |
"key": "1", | |
"value": "111" | |
} | |
""".data(using: .utf8)! | |
let valueNull = """ | |
{ | |
"key": "1", | |
"value": null | |
} | |
""".data(using: .utf8)! | |
let noValue = """ | |
{ | |
"key": "1" | |
} | |
""".data(using: .utf8)! | |
struct Model: Decodable { | |
fileprivate enum CodkingKeys : String, CodingKey { | |
case key | |
case value | |
} | |
let key: String | |
let value: String? | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodkingKeys.self) | |
key = try container.decode(String.self, forKey: .key) | |
value = try container.decodeIfPresent(String.self, forKey: .value) | |
} | |
} | |
let decoder = JSONDecoder() | |
do { | |
let model = try decoder.decode(Model.self, from: bothValues) | |
print("1: \(model)") | |
} catch { | |
print("1: \(error)") | |
} | |
do { | |
let model = try decoder.decode(Model.self, from: noValue) | |
print("2: \(model)") | |
} catch { | |
print("2: \(error)") | |
} | |
do { | |
let model = try decoder.decode(Model.self, from: valueNull) | |
print("3: \(model)") | |
} catch { | |
print("3: \(error)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment