Skip to content

Instantly share code, notes, and snippets.

@Arcovv
Created November 30, 2018 03:53
Show Gist options
  • Save Arcovv/f184600c8443822a4f3a36c500b7c58d to your computer and use it in GitHub Desktop.
Save Arcovv/f184600c8443822a4f3a36c500b7c58d to your computer and use it in GitHub Desktop.
Test `decodeIfPresent(_:forKey:)`
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