Last active
September 13, 2020 15:30
-
-
Save sunshinejr/a0dcdf846a17a1cdab5ca3f4b4aefd21 to your computer and use it in GitHub Desktop.
Using NSUserDefaults in Swift 4.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public let Defaults = UserDefaults.standard | |
open class DefaultsKeys { | |
fileprivate init() {} | |
} | |
open class DefaultsKey<ValueType>: DefaultsKeys { | |
public let _key: String | |
public init(_ key: String) { | |
self._key = key | |
super.init() | |
} | |
} | |
extension UserDefaults { | |
public subscript<T: Codable>(key: DefaultsKey<T>) -> T? { | |
get { | |
guard let data = object(forKey: key._key) as? Data else { return nil } | |
let decoder = JSONDecoder() | |
let dictionary = try! decoder.decode([String: T].self, from: data) | |
return dictionary["top"] | |
} | |
set { | |
guard let value = newValue else { return set(nil, forKey: key._key) } | |
let encoder = JSONEncoder() | |
let data = try! encoder.encode(["top": value]) | |
set(data, forKey: key._key) | |
} | |
} | |
} | |
// Usage | |
extension DefaultsKeys { | |
static let accessToken = DefaultsKey<AccessToken>("access_token") | |
} | |
guard let token = Defaults[.accessToken] else { return } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment