davidsteppenbeck / ObservableUserDefault

A Swift macro that adds accessor blocks to properties in `Observable` classes that read and write values in `UserDefaults`.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support optional types when providing an explicit key.

joeycarmello opened this issue · comments

I noticed that optional types work when using ObservableUserDefault without metadata, but fail to extract type information when a key is provided along with an optional type. This is important because providing keys is necessary for backwards compatibility, while most of our user defaults are optional. Relatedly, it would be nice if the api allowed optional defaultValue and store arguments to match the current AppStorage apis.

Successful

@ObservableUserDefault
@ObservationIgnored
public var lastViewed: Date?

Error

@ObservableUserDefault(.init(key: "LastViewedKey", defaultValue: nil, store: .standard))
@ObservationIgnored
public var lastViewed: Date?

The error is of the message Generic parameter 'DefaultValue' could not be inferred.

Attempting to provide type hinting gives a different error:

Error with hinting

@ObservableUserDefault(.init(key: "LastViewedKey", defaultValue: nil as Date?, store: .standard))
@ObservationIgnored
public var lastViewed: Date?

The error message of the above is '@ObservableUserDefault' unable to extract the required values from the argument

Thanks for the macro!

Thanks for pointing that out. Updated.

I added an extra argument that does not require a default value, so you won't have to specify nil.