Created
October 25, 2019 14:41
-
-
Save nicklockwood/a1fd598ea484a8180b1f7b48ae673319 to your computer and use it in GitHub Desktop.
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 | |
@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