Created
March 22, 2018 13:46
-
-
Save antonyalkmim/5090d87c194ff779199502ac85398177 to your computer and use it in GitHub Desktop.
UserDefaults Mockable
This file contains hidden or 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 | |
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