Using Property Wrappers with Codable

The way it is done in normal synthesizer is that:

  1. Generate CodingKeys if not already existed.
  2. Generate init(from:) if not already existed.

Further, the synthesizer uses appropriate variation of decodeIfPresent when the type is Optional, and normal decode otherwise. That's why it'd work nicely if your value is Double?--the synthesizer will use decodeIfPresent.

Now, what you need is something that is expanded to

struct Test: Decodable {
  var value: StringRepresentation<Double>?
}

but your code actually expands into (at least from codable synthesizer perspective)

struct Test: Decodable {
  var value: StringRepresentation<Double?>
}

And so the synthesizer will uses normal decode function, which will throw error if there is no key in the JSON data. The error is thrown before the initializer is called, so there's nothing from inside propertyWrapper that can be done.

We'll probably need a better system to express propertyWrapper with optional.

3 Likes