DefaultsKit leverages Swift 4
's powerful Codable capabilities and uses 50≈ or so lines of code to acomplish this.
Installation >> instructions
<<
Usage
Here's a simple get
example, with type inference on a complex object:
let person: Person = defaults.get(for: key)!
From the beginning...
Extend Keys
with your own keys and associated value type:
extension Keys {
static let nameKey = Key<String>("nameKey")
}
Instantiate, or get a shared
instance of Defaults
let defaults = Defaults() // or Defaults.shared
Then get
, set
or has
the desired key.
defaults.get(for: keys.nameKey) // Reads the `String` value
defaults.has(for: keys.nameKey) // Check if the `String` value exists
defaults.set("foo", for: keys.nameKey) // Sets a `String` value
DefaultsKit
will handle more complex objects. Just conform to the Codable protocol.
struct Person: Codable {
let name: String
let age: Int
let children: [Person]
}
Create a Key<T>
, then an instance of a Codable
and call set
.
let key = Key<Person>("personKey")
let person = Person(name: "Bonnie Greenwell", age: 80, children: [])
defaults.set(person, for: key)
To get the saved object:
let person = defaults.get(for: key)
person?.name // Bonnie Greenwell
person?.age // 80
Credits
SwiftyUserDefaults for the inspiration on Keys with an associated generic type.
License
DefaultsKit is released under the MIT license. See LICENSE for details.