TypesafeUserDefaults is a thin extension to UserDefaults that enables a type safe use. As a bonus, types that conform to Codable can be stored in the UserDefaults.
Define the keys:
enum UserKeys {
static let name = UserDefaults.Key<String>("name")
static let date = UserDefaults.Key<Date>("date")
}
Use them like the classic UserDefaults API:
UserDefaults.standard.set("Max Mustermann", forKey: UserKeys.name)
UserDefaults.standard.set(Date(), forKey: UserKeys.date)
let name = UserDefaults.standard.value(forKey: UserKeys.name)
let date = UserDefaults.standard.value(forKey: UserKeys.date)
Or use the convenient subscript:
UserDefaults.standard[UserKeys.name] = "Max Mustermann"
UserDefaults.standard[UserKeys.date] = Date()
let name = UserDefaults.standard[UserKeys.name]
let date = UserDefaults.standard[UserKeys.date]
The compiler will tell you if something is wrong:
// UIImage is not archivable in UserDefaults
let imageKey = UserDefaults.Key<UIImage>("image")
// Assigning value of type Date to a key that defined the value to be String
UserDefaults.standard[UserKeys.name] = Date()
// The return type does not match the type of the value
let date: Date = UserDefaults.standard[UserKeys.name]
Providing default values is simple as you define it in the same place with the key. No more need for using register
let pointsKey = UserDefaults.DefaultKey<Int>("points", 23)
var currentPoints = UserDefaults.standard[pointsKey] // 23
UserDefaults.standard[pointsKey] += 2
currentPoints = UserDefaults.standard[pointsKey] // 25
Conform to CustomDefaultsArchivable
:
struct User: CustomDefaultsArchivable {
let name: String
let date: Date
}
Define the key:
let userKey = UserDefaults.Key<User>("user")
Use the key:
UserDefaults.standard[userKey] = User(name: "Max Mustermann", date: Date())
let name = UserDefaults.standard[userKey]?.name
let date = UserDefaults.standard[userKey]?.date
>= Swift 4.1