How to add new property in Codable struct in SwiftUI

Issue #772

I use Codable structs in my apps for preferences, and bind them to SwiftUI views. If we add new properties to existing Codable, it can’t decode with old saved json as we require new properties. We can either do cutom decoding with container, but this can result in lots more code and mistakes if we have many properties inside our struct.

The quick workaround is to declare new properties as optional, and use a computed property to wrap that. The good news is Binding works with computed properties too, from the outside all looks like struct properties to SwiftUI

1
2
3
4
5
6
struct Preference: Codable {
var _redacts: Bool? = false
var redacts: Bool {
get { _redacts ?? false }
set { _redacts = newValue }
}

Comments

You need to set client_id and slot_id to show this AD unit. Please set it in _config.yml.