Last active
June 14, 2020 19:24
-
-
Save jeffery812/764d7eeca1f0761719851faf5efcab22 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
// https://www.vadimbulavin.com/advanced-guide-to-userdefaults-in-swift/ | |
// what is the difference between WWDC2019 https://devstreaming-cdn.apple.com/videos/wwdc/2019/402fd460n3p3w5c/402/402_whats_new_in_swift.pdf | |
// The marker protocol | |
protocol PropertyListValue {} | |
extension Data: PropertyListValue {} | |
extension String: PropertyListValue {} | |
extension Date: PropertyListValue {} | |
extension Bool: PropertyListValue {} | |
extension Int: PropertyListValue {} | |
extension Double: PropertyListValue {} | |
extension Float: PropertyListValue {} | |
// Every element must be a property-list type | |
extension Array: PropertyListValue where Element: PropertyListValue {} | |
extension Dictionary: PropertyListValue where Key == String, Value: PropertyListValue {} | |
struct Key: RawRepresentable { | |
let rawValue: String | |
} | |
extension Key: ExpressibleByStringLiteral { | |
init(stringLiteral: String) { | |
rawValue = stringLiteral | |
} | |
} | |
@propertyWrapper | |
struct UserDefault<T: PropertyListValue> { | |
let key: Key | |
var wrappedValue: T? { | |
get { UserDefaults.standard.value(forKey: key.rawValue) as? T } | |
set { UserDefaults.standard.set(newValue, forKey: key.rawValue) } | |
} | |
} | |
extension Key { | |
static let isFirstLaunch: Key = "isFirstLaunch" | |
} | |
struct Storage { | |
@UserDefault(key: .isFirstLaunch) | |
var isFirstLaunch: Bool | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment