Skip to content

Instantly share code, notes, and snippets.

@samrayner
Last active April 5, 2018 12:25
Show Gist options
  • Save samrayner/98e04f36869f9e504c1758edd12784d7 to your computer and use it in GitHub Desktop.
Save samrayner/98e04f36869f9e504c1758edd12784d7 to your computer and use it in GitHub Desktop.
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