Created
March 21, 2022 15:52
-
-
Save johnclayton/006d25030315ee16c6371d3b20cc3c0f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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