To starting using UserDefaultsStorable, simply declare a UserDefaults property with a given key and a default value.
enum Defaults {
@UserDefault(key: "username")
static var username: String = "mrfour0004"
// Of course type inference works as expected
@UserDefault(key: "displayName")
static var displayName = "mrfour"
// If the stored type is Optional, initial value is not required as normal optional properties
@UserDefault(key: "token")
static var token: String?
}
print(Defaults.username) // guest
print(Defaults.token) // nil
Conforms types to UserDefaultsStorable
You may have custom types and want them can be stored in UserDefaults. Just conform them to the protocol UserDefaultsStorable, and implement the required userDefaultsBridge property.
struct Point {
let x: Int, y: Int
}
extension Point: UserDefaultsStorable {
static var userDefaultsBridge: UserDefautsBridge<Point> {
UserDefaultsBridge(
serialization: { point in
return ["x": point.x, "y": point.y]
},
deserialization: { object in
guard
let dict = object as? [String: Int]
let x = dict["x"] as? Int,
let y = dict["y"] as? Int
else { return nil }
return Point(x: x, y: y)
}
}
}
}
If the type conforms to Codable as well, then there’s already a default implementation of userDefaultsBridge.
struct Point: Codable, UserDefaultsStorable {
let x: Int, y: Int
}
enum Defaults {
@UserDefault(key: "point")
static var point: Point?
}
Observation
enum Defaults {
@UserDefault(key: "username")
static var username: String = "guest"
}
let observation = Defaults.$username.observe(withOptions: [.old, .new]) { change in
print(change.newValue) // print Optional("guest")
print(change.oldValue) // print Optional("mrfour")
}
let newValueObservation = Defaults.$username.observe { newValue in
print(newValue) // print Optional("mrfour")
}
Defaults.username = "mrfour"
License
UserDefaultsStorable is available under the MIT license. See the LICENSE file for more info.
UserDefaultsStorable
UserDefaultsStorable provides an easy, strongly-typed way to access properties in UserDefaults.
Summary
Requirement
Installation
Cocoapods
Swift Package Manager
Usage
To starting using
UserDefaultsStorable
, simply declare aUserDefaults
property with a given key and a default value.Conforms types to
UserDefaultsStorable
You may have custom types and want them can be stored in
UserDefaults
. Just conform them to the protocolUserDefaultsStorable
, and implement the requireduserDefaultsBridge
property.If the type conforms to
Codable
as well, then there’s already a default implementation ofuserDefaultsBridge
.Observation
License
UserDefaultsStorable is available under the MIT license. See the LICENSE file for more info.