Skip to content

Instantly share code, notes, and snippets.

@marty-suzuki
Created June 9, 2019 04:40
Show Gist options
  • Save marty-suzuki/a336f8dfc4d0600997eca5f66deea396 to your computer and use it in GitHub Desktop.
Save marty-suzuki/a336f8dfc4d0600997eca5f66deea396 to your computer and use it in GitHub Desktop.
Sample usage of Swift 5.1 dynamicMemberLookup that supports KeyPath.
import Foundation
@dynamicMemberLookup
final class DynamicUserDefaults {
static var standard: DynamicUserDefaults {
return DynamicUserDefaults(.standard)
}
private let keys = Keys()
private let defaults: UserDefaults
init(_ defaults: UserDefaults) {
self.defaults = defaults
}
subscript<T>(dynamicMember keyPath: KeyPath<Keys, Key<T>>) -> T? {
get {
let key = keys[keyPath: keyPath]
return defaults.object(forKey: key.rawKey) as? T
}
set {
let key = keys[keyPath: keyPath]
defaults.set(newValue, forKey: key.rawKey)
}
}
}
extension DynamicUserDefaults {
struct Keys {}
struct Key<T> {
let rawKey: String
}
}
extension DynamicUserDefaults.Keys {
var username: DynamicUserDefaults.Key<String> {
return .init(rawKey: "user-name")
}
}
let ud = DynamicUserDefaults.standard
print(ud.username) // nil
ud.username = "Michael J. Fox"
print(ud.username) // Optional("Michael J. Fox")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment