Defaults.swift 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // SwiftyUserDefaults
  3. //
  4. // Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in all
  14. // copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. // SOFTWARE.
  23. //
  24. import Foundation
  25. /// Global shortcut for `UserDefaults.standard`
  26. ///
  27. /// **Pro-Tip:** If you want to use shared user defaults, just
  28. /// redefine this global shortcut in your app target, like so:
  29. /// ~~~
  30. /// var Defaults = DefaultsAdapter(defaults: UserDefaults(suiteName: "com.my.app")!, keyStore: DefaultsKeys())
  31. /// ~~~
  32. public var Defaults = DefaultsAdapter<DefaultsKeys>(defaults: .standard, keyStore: .init())
  33. public extension UserDefaults {
  34. /// Returns `true` if `key` exists
  35. func hasKey<T>(_ key: DefaultsKey<T>) -> Bool {
  36. return object(forKey: key._key) != nil
  37. }
  38. /// Removes value for `key`
  39. func remove<T>(_ key: DefaultsKey<T>) {
  40. removeObject(forKey: key._key)
  41. }
  42. /// Removes all keys and values from user defaults
  43. /// Use with caution!
  44. /// - Note: This method only removes keys on the receiver `UserDefaults` object.
  45. /// System-defined keys will still be present afterwards.
  46. func removeAll() {
  47. for (key, _) in dictionaryRepresentation() {
  48. removeObject(forKey: key)
  49. }
  50. }
  51. }
  52. internal extension UserDefaults {
  53. func number(forKey key: String) -> NSNumber? {
  54. return object(forKey: key) as? NSNumber
  55. }
  56. func decodable<T: Decodable>(forKey key: String) -> T? {
  57. guard let decodableData = data(forKey: key) else { return nil }
  58. return try? JSONDecoder().decode(T.self, from: decodableData)
  59. }
  60. /// Encodes passed `encodable` and saves the resulting data into the user defaults for the key `key`.
  61. /// Any error encoding will result in an assertion failure.
  62. func set<T: Encodable>(encodable: T, forKey key: String) {
  63. do {
  64. let data = try JSONEncoder().encode(encodable)
  65. set(data, forKey: key)
  66. } catch {
  67. assertionFailure("Failure encoding encodable of type \(T.self): \(error.localizedDescription)")
  68. }
  69. }
  70. }