SHARE
TWEET

Untitled

a guest Jun 27th, 2019 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. @propertyWrapper
  2. public struct UserDefault<T>: UserDefaultSpec {
  3.   let key: String
  4.   let defaultValue: T
  5.  
  6.   public init(_ key: String, defaultValue: T) {
  7.     self.key = key
  8.     self.defaultValue = defaultValue
  9.   }
  10.  
  11.   public var value: T {
  12.     get {
  13.       UserDefaults.standard[key] ?? defaultValue
  14.     }
  15.     set {
  16.       UserDefaults.standard[key] = newValue
  17.     }
  18.   }
  19. }
  20.  
  21. // GRRR why don't you work?!
  22. public extension UserDefault where T: RawRepresentable {
  23.   var value: T {
  24.     get {
  25.       if let rawValue = UserDefaults.standard.value(forKey: key) as? T.RawValue {
  26.         return T(rawValue: rawValue)!
  27.       }
  28.      
  29.       return defaultValue
  30.     }
  31.     set {
  32.       UserDefaults.standard.set(newValue.rawValue, forKey: key)
  33.     }
  34.   }
  35. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top