Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created September 10, 2020 22:47
Show Gist options
  • Save IanKeen/c2d6926ef3256efa90a1e899fe69abf4 to your computer and use it in GitHub Desktop.
Save IanKeen/c2d6926ef3256efa90a1e899fe69abf4 to your computer and use it in GitHub Desktop.
PropertyWrapper: AppStorage backport
@propertyWrapper
struct AppStorage<Value>: DynamicProperty {
let key: String
let defaultValue: Value
init(wrappedValue defaultValue: Value, _ key: String) {
self.key = key
self.defaultValue = defaultValue
self._wrappedValue = State(wrappedValue: UserDefaults.standard.object(forKey: key) as? Value ?? defaultValue)
}
@State var wrappedValue: Value {
didSet { UserDefaults.standard.set(wrappedValue, forKey: key) }
}
var projectedValue: Binding<Value> {
return Binding(
get: { wrappedValue },
set: { wrappedValue = $0 }
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment