Skip to content

Instantly share code, notes, and snippets.

@johnclayton
Created March 21, 2022 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnclayton/006d25030315ee16c6371d3b20cc3c0f to your computer and use it in GitHub Desktop.
Save johnclayton/006d25030315ee16c6371d3b20cc3c0f to your computer and use it in GitHub Desktop.
import Foundation
extension UserDefaults {
struct Key {
typealias RawValue = String
let rawValue: RawValue
init(_ string: String) {
self.rawValue = string
}
}
func value<Value>(forKey key: Key) -> Value? {
value(forKey: key.rawValue) as? Value
}
func set<Value>(value: Value, forKey key: Key) {
set(value, forKey: key.rawValue)
}
// One could also add overloads for the standard types...
func bool(forKey key: Key) -> Bool {
bool(forKey: key.rawValue)
}
}
extension UserDefaults.Key: ExpressibleByStringLiteral {
init(stringLiteral: String) {
self.init(stringLiteral)
}
}
extension UserDefaults.Key {
static let isFooEnabledKey: Self = "isFooEnabledKey"
}
let defaults = UserDefaults.standard
var value = defaults.bool(forKey: .isFooEnabledKey)
print("initialvalue: \(value)")
defaults.set(value: true, forKey: .isFooEnabledKey)
value = defaults.bool(forKey: .isFooEnabledKey)
print("currentValue: \(value)")
defaults.set(value: false, forKey: .isFooEnabledKey)
value = defaults.bool(forKey: .isFooEnabledKey)
print("currentValue: \(value)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment