iOS | macOS | watchOS | tvOS |
---|---|---|---|
Define Static Keys for easy access to data stored in UserDefaults
extension DefaultsKeys {
static let key = DefaultsKey<String>("key")
static let number = DefaultsKey<Double>("number")
static let condition = DefaultsKey<Bool>("condition")
// eg. struct SomeCodable : Codeable { ... }
static let codeable = DefaultsKey<SomeCodable>("somecodeable")
}
Static keys
UserDefaults.standard[.key] = "Value"
UserDefaults.standard[.number] = -3.4
UserDefaults.standard[.condition] = true
UserDefaults.standard[.codeable] = SomeCodable()
String Keys
UserDefaults.standard["key"] = "Value"
UserDefaults.standard["number"] = -3.4
UserDefaults.standard["condition"] = true
Static Keys
var string = UserDefaults.standard[.key]
// string = Optional<String>
if UserDefaults.standard[.condition] {
// true
}
let someCodable: SomeCodable? = UserDefaults.standard[.codeable]
// someCodable = Optional<SomeCodable>
String Keys
let object = UserDefaults.standard["key"]
// object = Optional<Any>
let string = UserDefaults.standard.string("key")
// string = Optional<String>
Static Keys
UserDefaults.standard[.key] += ". Other value."
UserDefaults.standard[.number] *= 1.2
String Keys
UserDefaults.standard["key"] = UserDefaults.standard.string(forKey: "key") ?? "" + ". Other value."
UserDefaults.standard["number"] = UserDefaults.standard.double("number") * 1.2
UserDefaults is available through Carthage. To install just write into your Cartfile:
github "divadretlaw/UserDefaults"
See LICENSE
Copyright ยฉ 2018 David Walter (www.davidwalter.at)