UserDefaultsBacked.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. private protocol OptionalProtocol {
  16. var isNil: Bool { get }
  17. }
  18. extension Optional: OptionalProtocol {
  19. public var isNil: Bool { self == nil }
  20. }
  21. /// Property initializer for user defaults. Value is always read from or written to a named user defaults store.
  22. @propertyWrapper struct UserDefaultsBacked<Value> {
  23. let key: String
  24. let defaultValue: Value
  25. let storage: UserDefaults
  26. var wrappedValue: Value {
  27. get {
  28. let value = storage.value(forKey: key) as? Value
  29. return value ?? defaultValue
  30. }
  31. set {
  32. if let optional = newValue as? OptionalProtocol, optional.isNil {
  33. storage.removeObject(forKey: key)
  34. } else {
  35. storage.setValue(newValue, forKey: key)
  36. }
  37. }
  38. }
  39. }
  40. /// Initialize and set default value for user default backed properties that can be optional (model path).
  41. extension UserDefaultsBacked where Value: ExpressibleByNilLiteral {
  42. init(key: String, storage: UserDefaults) {
  43. self.init(key: key, defaultValue: nil, storage: storage)
  44. }
  45. }
  46. /// Initialize and set default value for user default backed properties that are strings (model download url, model hash).
  47. extension UserDefaultsBacked where Value: ExpressibleByStringLiteral {
  48. init(key: String, storage: UserDefaults) {
  49. self.init(key: key, defaultValue: "", storage: storage)
  50. }
  51. }
  52. /// Initialize and set default value for user default backed properties that are int (model size).
  53. extension UserDefaultsBacked where Value: ExpressibleByIntegerLiteral {
  54. init(key: String, storage: UserDefaults) {
  55. self.init(key: key, defaultValue: 0, storage: storage)
  56. }
  57. }