Skip to content

Instantly share code, notes, and snippets.

@r-plus
Last active September 14, 2019 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r-plus/0d243272ac2247305551100c129da344 to your computer and use it in GitHub Desktop.
Save r-plus/0d243272ac2247305551100c129da344 to your computer and use it in GitHub Desktop.
method for don't throw Swift.Error and keep default value if key is not present in json.
extension KeyedDecodingContainerProtocol {
func decode<T: Decodable>(into: inout T, forKey key: Self.Key) {
guard let tmp = try? self.decode(T.self, forKey: key) else { return }
into = tmp
}
}
class A: Decodable {
var hoge = "1"
enum CodingKeys: CodingKey {
case hoge
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
container.decode(into: &hoge, forKey: .hoge)
}
}
let str = "{}"
let data = str.data(using: .utf8)!
let d = JSONDecoder()
let a2 = try! d.decode(A.self, from: data)
print(a2.hoge) // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment