Skip to content

Instantly share code, notes, and snippets.

@antonyalkmim
Created March 22, 2018 13:46
Show Gist options
  • Save antonyalkmim/5090d87c194ff779199502ac85398177 to your computer and use it in GitHub Desktop.
Save antonyalkmim/5090d87c194ff779199502ac85398177 to your computer and use it in GitHub Desktop.
UserDefaults Mockable
import Foundation
protocol UserDefaultsDelegate: class {
func theObject(forKey key: String) -> Any?
func setTheObject(_ object: Any, forKey key: String)
func removeTheObject(forKey key: String)
func synchronizeAll()
}
class UserDefaultsService: NSObject {
static let shared = UserDefaultsService()
weak var delegate: UserDefaultsDelegate?
override init() {
super.init()
delegate = UserDefaults.standard
}
func get<T>(_ typeOf: T.Type, forKey key: String) -> T? {
return delegate?.theObject(forKey: key) as? T
}
func set<T>(_ value: T, forKey key: String) {
delegate?.setTheObject(value, forKey: key)
}
func removeObject(forKey key: String) {
delegate?.removeTheObject(forKey: key)
}
func synchronize() {
delegate?.synchronizeAll()
}
}
extension UserDefaults: UserDefaultsDelegate {
func theObject(forKey key: String) -> Any? {
return self.object(forKey: key)
}
func setTheObject(_ object: Any, forKey key: String) {
self.set(object, forKey: key)
}
func removeTheObject(forKey key: String) {
self.removeObject(forKey: key)
}
func synchronizeAll() {
self.synchronize()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment