Skip to content

Instantly share code, notes, and snippets.

@mezhevikin
Created July 11, 2023 13:08
Show Gist options
  • Save mezhevikin/9168cd657da61a7fca6d16babb8f12f0 to your computer and use it in GitHub Desktop.
Save mezhevikin/9168cd657da61a7fca6d16babb8f12f0 to your computer and use it in GitHub Desktop.
ContentView.swift
import SwiftUI
struct ContentView: View {
@Persistent(key: "isActive")
var isActive: Bool = false
var body: some View {
VStack(spacing: 20) {
Text(isActive ? "Yes" : "No")
Button("Toogle") {
isActive.toggle()
}
}
}
}
@propertyWrapper
struct Persistent<Value>: DynamicProperty {
let key: String
let defaultValue: Value
let store: UserDefaults
init(
wrappedValue defaultValue: Value,
key: String,
store: UserDefaults = .standard
) {
self.defaultValue = defaultValue
self.key = key
self.store = store
self.value = State<Value>(
initialValue: store.object(forKey: key) as? Value ?? defaultValue
)
}
private var value: State<Value>
var wrappedValue: Value {
get {
value.wrappedValue
}
nonmutating set {
DispatchQueue.main.async {
value.wrappedValue = newValue
if let optional = newValue as? AnyOptional, optional.isNil {
store.removeObject(forKey: key)
} else {
store.set(newValue, forKey: key)
}
}
}
}
var projectedValue: Binding<Value> {
value.projectedValue
}
}
extension Persistent where Value: ExpressibleByNilLiteral {
init(key: String, store: UserDefaults = .standard) {
self.init(wrappedValue: nil, key: key, store: store)
}
}
protocol AnyOptional {
var isNil: Bool { get }
}
extension Optional: AnyOptional {
var isNil: Bool { self == nil }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment