Skip to content

Instantly share code, notes, and snippets.

@zhihuitang
Last active June 14, 2020 19:24
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 zhihuitang/764d7eeca1f0761719851faf5efcab22 to your computer and use it in GitHub Desktop.
Save zhihuitang/764d7eeca1f0761719851faf5efcab22 to your computer and use it in GitHub Desktop.
// 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