Created
October 23, 2019 07:10
-
-
Save KaQuMiQ/441c7331f02d6150f9cf50a8e30c45cd to your computer and use it in GitHub Desktop.
UserDefaults property wrapper
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 | |
internal protocol AnyOptional { | |
var isNone: Bool { get } | |
} | |
extension Optional: AnyOptional { | |
var isNone: Bool { | |
switch self { | |
case .none: return true | |
case .some: return false | |
} | |
} | |
} | |
@propertyWrapper | |
internal final class UserDefaults<Wrapped> { | |
private let identifier: String | |
private let `default`: Wrapped | |
internal init(_ identifier: String, `default`: Wrapped) { | |
self.identifier = identifier | |
self.default = `default` | |
} | |
internal var wrappedValue: Wrapped { | |
get { | |
return UserDefaults.standard.object(forKey: identifier) as? Wrapped ?? `default` | |
} | |
set { | |
if (newValue as? AnyOptional)?.isNone ?? false { | |
UserDefaults.standard.removeObject(forKey: identifier) | |
} else { | |
UserDefaults.standard.set(newValue, forKey: identifier) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment