Skip to content

Instantly share code, notes, and snippets.

@danielctull
Created October 7, 2019 14:09
Show Gist options
  • Save danielctull/27326609f338ec0f25cfb3c4cfd73ecf to your computer and use it in GitHub Desktop.
Save danielctull/27326609f338ec0f25cfb3c4cfd73ecf to your computer and use it in GitHub Desktop.
UserDefaults Key with a Property Wrapper
import Foundation
// MARK:- Usage
extension UserDefaults.Key where Value == Bool {
static let shouldDoSomething = Self(name: "shouldDoSomething", default: false)
}
struct View {
@UserDefault(key: .shouldDoSomething) private var shouldDoSomething
func f() {
guard shouldDoSomething else { return }
// DO SOMETHING
}
}
// MARK:- UserDefault Property Wrapper
@propertyWrapper
public final class UserDefault<Value> {
private let defaults: UserDefaults
private let key: UserDefaults.Key<Value>
public init(key: UserDefaults.Key<Value>, defaults: UserDefaults = .standard) {
self.defaults = defaults
self.key = key
}
public var wrappedValue: Value {
get { defaults.value(for: key) ?? key.default }
set { defaults.set(newValue, for: key) }
}
}
// MARK:- UserDefaults Key
extension UserDefaults {
/// A wrapper around a user defaults key, to enable a type-safe
/// way of accessing values in an instance of UserDefaults.
public struct Key<Value> {
fileprivate let name: String
fileprivate let `default`: Value
public init(name: String, default: Value) {
self.name = name
self.default = `default`
}
}
/// Sets the value of the specified key.
///
/// - Parameters:
/// - value: The value to store in the defaults database.
/// - key: The key with which to associate the value.
public func set<Value>(_ value: Value?, for key: UserDefaults.Key<Value>) {
set(value, forKey: key.name)
}
/// Returns the value associated with the specified key.
///
/// - Parameter key: The key which is associated with the value.
/// - Returns: The value associated with the specified key, or nil if the key was not found.
public func value<Value>(for key: UserDefaults.Key<Value>) -> Value? {
return object(forKey: key.name) as? Value
}
/// Removes the value of the specified key.
///
/// - Parameter key: The key whose value you want to remove.
public func remove<Value>(for key: UserDefaults.Key<Value>) {
removeObject(forKey: key.name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment