A Swift extension to use UserDefaults
in a simple, elegant, type-safe way. This library also supports key-value observing with block.
- macOS 10.9+ / iOS 8.0+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 8+
- Swift 3.0+
This library aims to make it super-easy to read, write and observeing the defaults from UserDefaults
, even supporting coding/decoding with NSKeyedArchiver
.
let Defaults = UserDefaults.standard
let Name = "Name"
let Age = "Age"
let Photo = "Photo"
class Man: NSObject {
let name: String?
let age: Int
let photo: NSImage?
override init() {
name = Defaults.string(forKey: Name)
age = Defaults.integer(forKey: Age)
if let photoData = Defaults.data(forKey: Photo) {
photo = NSKeyedUnarchiver.unarchiveObject(with: photoData) as? NSImage
} else {
photo = nil
}
super.init()
Defaults.addObserver(self, forKeyPath: Age, options: [.old, .new], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath else {
return
}
guard let change = change,
let oldValue = change[.oldKey], let newValue = change[.newKey] else {
return
}
switch keyPath {
case Age:
print("\(oldValue) -> \(newValue)")
default:
break
}
}
deinit {
Defaults.removeObserver(self, forKeyPath: Age)
}
}
let Defaults = EasyPreference(defaults: .standard)
let Name: PreferenceKey<String> = "Name"
let Age: PreferenceKey<Int> = "Age"
let Photo: PreferenceKey<NSImage> = "Photo"
class Man {
let name: String?
let age: Int
let photo: NSImage?
init() {
name = Defaults[Name]
age = Defaults[Age]
photo = Preference.object(for: Photo)
Defaults.subscribe(key: Age) { change in
print("\(change.oldValue) -> \(change.newValue)")
}
}
}
Add the project to your Cartfile
:
github "XQS6LB3A/EasyPreference"
Add the project to your Package.swift
file:
let package = Package(
dependencies: [
.Package(url: "https://github.com/XQS6LB3A/EasyPreference", majorVersion: 0)
]
)
EasyPreference is available under the MIT license. See the LICENSE file.