DefaultsKit leverages Swift 4's powerful Codable capabilities to provide a Simple and Strongly Typed wrapper on top of UserDefaults. It uses less than 70 lines of code to acomplish this.
Installation >> instructions
<<
Instantiate, or get a shared
instance of Defaults
let defaults = Defaults() // or Defaults.shared
Then:
// Define a key
let key = Key<String>("someKey")
// Set a value
defaults.set("Codable FTW 😃", for: key)
// Read the value back
defaults.get(for: key) // Output: Codable FTW 😃
if defaults.has(for: key) {
// Do your thing
}
To persist a complex object just conform to the Codable protocol:
struct Person: Codable {
let name: String
let age: Int
}
Then:
// Create a key
let key = Key<Person>("personKey")
// Get an instance of your Codable conforming enum, struct or class
let person = Person(name: "Bonnie Greenwell", age: 80)
// Set the value
defaults.set(person, for: key)
And finally:
// Read it back
let person = defaults.get(for: key)
person?.name // Bonnie Greenwell
person?.age // 80
You can also use nested object as long as they conform to the Codable
protocol:
enum Pet: String, Codable {
case cat
case dog
}
struct Person: Codable {
let name: String
let pets: [Pet]
}
// Get a Codable conforming instante
let person = Person(name: "Claire", pets: [.cat])
// Set the value
defaults.set(person, for: key)
// And read it back
let person = defaults.get(for: key)
person?.name // Claire
person?.pets.first // cat
DefaultsKit is released under the MIT license. See LICENSE for details.