Chapter 15: Challenge 2 - Persisting the filter between app launches

Persisting doesn’t work because didSet in Settings.keyworks is never called. Does anyone has an idea what goes wrong?

Apparently the line self.settings.keywords.append(new) in SettingsView is not triggering the didSet in the keywords property inside Settings model

Thanks miibpa,

do you think it’s a Swift bug?

taufi

Yep It seem to be a bug in Swift 5.2 :frowning:

1 Like

Read on ‘stackoverflow’ that structs like ‘FilterKeywords’ aren’t KVO compatible. The value has to be a subclass of NSObject using @objc dynamic properties. So adding a value in the array won’t trigger ‘willSet/didSet’

My solution was to use a temporary array instead and replace the whole array in the ‘AddKeywordView’ closure which triggered the ‘didSet’ method as expected.

//Reassign array to trigger ‘didSet’
let saveKeywords = self.settings.keywords + [new]
self.settings.keywords = saveKeywords

Another possible way is to use the underlying ‘wrappedValue’ of the binding property, maybe a hack…

self.$settings.keywords.wrappedValue = new

1 Like

@afrank Thank you for sharing your solution - much appreciated!