项目作者: V8tr

项目描述 :
Swifty UserDefaults property wrapper with statically-typed keys and change observations. https://www.vadimbulavin.com/advanced-guide-to-userdefaults-in-swift/
高级语言: Swift
项目地址: git://github.com/V8tr/UserDefaultsPropertyWrapper.git
创建时间: 2020-04-17T14:42:15Z
项目社区:https://github.com/V8tr/UserDefaultsPropertyWrapper

开源协议:The Unlicense

下载


Article related to this project


UserDefaultsPropertyWrapper

A sample project showing how to implement a UserDefaults property wrapper in Swift. The property wrapper has statically typed keys and provides a conveniece to observe UserDefaults changes.

Usage:

  1. // Declare a new key
  2. extension Key {
  3. static let isFirstLaunch: Key = "isFirstLaunch"
  4. }
  5. struct Storage {
  6. // Use the property wrapper to add new value to `UserDefaults`
  7. @UserDefault(key: .isFirstLaunch)
  8. var isFirstLaunch: Bool?
  9. }
  10. // Initialize the storage
  11. var storage = Storage()
  12. // Observe user default changes
  13. var observation = storage.$isFirstLaunch.observe { old, new in
  14. print("Changed from: \(old) to \(new)")
  15. }
  16. // Make some changes
  17. storage.isFirstLaunch = true
  18. storage.isFirstLaunch?.toggle()
  19. `

It will print:

  1. Changed from: Optional(false) to Optional(true)
  2. Changed from: Optional(true) to Optional(false)