Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
Created October 25, 2019 14:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicklockwood/a1fd598ea484a8180b1f7b48ae673319 to your computer and use it in GitHub Desktop.
Save nicklockwood/a1fd598ea484a8180b1f7b48ae673319 to your computer and use it in GitHub Desktop.
import Foundation
@propertyWrapper
struct ZeroDefaulting: Codable {
var wrappedValue: Int?
init(wrappedValue: Int?) {
print("set:", wrappedValue ?? "nil")
self.wrappedValue = wrappedValue
}
init(from decoder: Decoder) throws {
self.wrappedValue = (try? Int(from: decoder)) ?? 0
print("decoded:", wrappedValue!)
}
}
struct Foo: Codable {
@ZeroDefaulting var bar: Int!
}
let data = "{}".data(using: .utf8)!
let foo = try! JSONDecoder().decode(Foo.self, from: data)
print(foo.bar)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment