
1- Extension:
This file contains hidden or 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 | |
| enum UserDefaultKeys: String { | |
| case key1 | |
| case key2 | |
| case key3 | |
| } | |
| extension UserDefaults { | |
| func removeObject(forKey key: UserDefaultKeys) { | |
| removeObject(forKey: key.rawValue) | |
| } | |
| subscript<Value>(key: UserDefaultKeys) -> Value? { | |
| get { object(forKey: key.rawValue) as? Value } | |
| set { set(newValue, forKey: key.rawValue) } | |
| } | |
| } | |
| func testExtension() { | |
| let userDefaults = UserDefaults.standard | |
| userDefaults[.key1] = "Hasancan" | |
| print(userDefaults[.key1] ?? "nil") | |
| userDefaults.removeObject(forKey: .key1) | |
| print(userDefaults[.key1] ?? "nil") | |
| } |
2- Property Wrappers:
This file contains hidden or 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 | |
| @propertyWrapper | |
| public struct UserDefaultsStorage<Value> { | |
| let key: String | |
| public init(_ key: String) { | |
| self.key = key | |
| } | |
| public var wrappedValue: Value? { | |
| get { | |
| return UserDefaults.standard.object(forKey: key) as? Value | |
| } | |
| set { | |
| if newValue != nil { | |
| UserDefaults.standard.set(newValue, forKey: key) | |
| } else { | |
| UserDefaults.standard.removeObject(forKey: key) | |
| } | |
| } | |
| } | |
| } | |
| public struct UserDefaultConfig { | |
| @UserDefaultsStorage("key1") | |
| public static var key1: String? | |
| @UserDefaultsStorage("key2") | |
| public static var key2: Bool? | |
| @UserDefaultsStorage("key3") | |
| public static var key3: Int? | |
| } | |
| func testPropertyWrapperExtension() { | |
| UserDefaultConfig.key1 = "Hasancan" | |
| print(UserDefaultConfig.key1 ?? "nil") | |
| UserDefaultConfig.key1 = nil | |
| print(UserDefaultConfig.key1 ?? "nil") | |
| } |
