Skip to content

Instantly share code, notes, and snippets.

@Otbivnoe
Last active March 11, 2022 09:22
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Otbivnoe/04b8bd7984fba0cb58ca7f136fd95582 to your computer and use it in GitHub Desktop.
Save Otbivnoe/04b8bd7984fba0cb58ca7f136fd95582 to your computer and use it in GitHub Desktop.
extension UserDefaults {
subscript<T>(key: String) -> T? {
get {
return value(forKey: key) as? T
}
set {
set(newValue, forKey: key)
}
}
subscript<T: RawRepresentable>(key: String) -> T? {
get {
if let rawValue = value(forKey: key) as? T.RawValue {
return T(rawValue: rawValue)
}
return nil
}
set {
set(newValue?.rawValue, forKey: key)
}
}
}
@FlixMa
Copy link

FlixMa commented Apr 16, 2018

You can actually make it even less redundant:

Replace (line 19):
set(newValue?.rawValue, forKey: key)
with:
self[key] = newValue?.rawValue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment