Last active
April 5, 2018 12:25
-
-
Save samrayner/98e04f36869f9e504c1758edd12784d7 to your computer and use it in GitHub Desktop.
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 | |
extension UserDefaults { | |
enum Key: String { | |
case customKey | |
} | |
//can be used for KVO | |
@objc dynamic var customKey: Int { | |
return get(.customKey) ?? 0 | |
} | |
func set<T>(_ value: T?, for key: Key) { | |
if let value = value { | |
set(value, forKey: key.rawValue) | |
} else { | |
removeObject(forKey: key.rawValue) | |
} | |
} | |
func get<T>(_ key: Key) -> T? { | |
return object(forKey: key.rawValue) as? T | |
} | |
func removeAllObjects() { | |
dictionaryRepresentation().keys.forEach(removeObject(forKey:)) | |
} | |
} | |
UserDefaults.set(true, for: .customKey) | |
let bool: Bool? = UserDefaults.get(.customKey) //Optional<True> | |
let int: Int? = UserDefaults.get(.customKey) //nil | |
UserDefaults.set(123, for: .customKey) | |
let int: Int? = UserDefaults.get(.customKey) //Optional<123> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment