Skip to content

Instantly share code, notes, and snippets.

@jimmythai
Created November 11, 2017 08:29
Show Gist options
  • Select an option

  • Save jimmythai/ca957b80d1b4cbd19142d73bd6593f90 to your computer and use it in GitHub Desktop.

Select an option

Save jimmythai/ca957b80d1b4cbd19142d73bd6593f90 to your computer and use it in GitHub Desktop.
import Foundation
// MARK: UserDefaults extension
extension UserDefaults {
struct SomeApp: UserDefaultable {
enum UserDefaultKey: String {
case someItem
}
private init() {}
}
}
// MARK: UserDefaultable protocol
public protocol UserDefaultable: KeyNamespaceable {
associatedtype UserDefaultKey: RawRepresentable
}
public extension UserDefaultable where UserDefaultKey.RawValue == String {
public static func setValue(_ value: Any?, forKey key: UserDefaultKey) {
let key = namespace(key)
UserDefaults.standard.setValue(value, forKey: key)
}
public static func setCustomObject(_ customObject: Any?, forKey key: UserDefaultKey) {
let key = namespace(key)
guard let customObject = customObject else { return }
let encodedData = NSKeyedArchiver.archivedData(withRootObject: customObject)
UserDefaults.standard.setValue(encodedData, forKey: key)
}
public static func object(forKey key: UserDefaultKey) -> Any? {
let key = namespace(key)
return UserDefaults.standard.object(forKey: key)
}
public static func customObject(forKey key: UserDefaultKey) -> Any? {
let key = namespace(key)
guard let encodedData = UserDefaults.standard.object(forKey: key) as? Data else { return nil }
return NSKeyedUnarchiver.unarchiveObject(with: encodedData)
}
public static func removeObject(forKey key: UserDefaultKey) {
let key = namespace(key)
UserDefaults.standard.removeObject(forKey: key)
}
}
// MARK: KeyNamespaceable protocol
public protocol KeyNamespaceable {}
public extension KeyNamespaceable {
public static func namespace<Key>(_ key: Key) -> String where Key: RawRepresentable {
return "\(Self.self).\(key.rawValue)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment