Defaults also support the above types wrapped in Array, Set, Dictionary, Range, ClosedRange, and even wrapped in nested types. For example, [[String: Set<[String: Int]>]].
You declare the defaults keys upfront with a type and default value.
The key name must be ASCII, not start with @, and cannot contain a dot (.).
import Defaults
extension Defaults.Keys {
static let quality = Key<Double>("quality", default: 0.8)
// ^ ^ ^ ^
// Key Type UserDefaults name Default value
}
You can then access it as a subscript on the Defaults global:
Defaults[.quality]
//=> 0.8
Defaults[.quality] = 0.5
//=> 0.5
Defaults[.quality] += 0.1
//=> 0.6
Defaults[.quality] = "🦄"
//=> [Cannot assign value of type 'String' to type 'Double']
You can also declare optional keys for when you don’t want to declare a default value upfront:
extension Defaults.Keys {
static let name = Key<Double?>("name")
}
if let name = Defaults[.name] {
print(name)
}
The default value is then nil.
You can also specify a dynamic default value. This can be useful when the default value may change during the lifetime of the app:
extension Defaults.Keys {
static let camera = Key<AVCaptureDevice?>("camera") { .default(for: .video) }
}
Enum example
enum DurationKeys: String, Defaults.Serializable {
case tenMinutes = "10 Minutes"
case halfHour = "30 Minutes"
case oneHour = "1 Hour"
}
extension Defaults.Keys {
static let defaultDuration = Key<DurationKeys>("defaultDuration", default: .oneHour)
}
Defaults[.defaultDuration].rawValue
//=> "1 Hour"
(This works as long as the raw value of the enum is any of the supported types)
Codable example
struct User: Codable, Defaults.Serializable {
let name: String
let age: String
}
extension Defaults.Keys {
static let user = Key<User>("user", default: .init(name: "Hello", age: "24"))
}
Defaults[.user].name
//=> "Hello"
Use keys directly
You are not required to attach keys to Defaults.Keys.
let isUnicorn = Defaults.Key<Bool>("isUnicorn", default: true)
Defaults[isUnicorn]
//=> true
SwiftUI support
@Default
You can use the @Default property wrapper to get/set a Defaults item and also have the view be updated when the value changes. This is similar to @State.
extension Defaults.Keys {
static let hasUnicorn = Key<Bool>("hasUnicorn", default: false)
}
struct ContentView: View {
@Default(.hasUnicorn) var hasUnicorn
var body: some View {
Text("Has Unicorn: \(hasUnicorn)")
Toggle("Toggle", isOn: $hasUnicorn)
Button("Reset") {
_hasUnicorn.reset()
}
}
}
Note that it’s @Default, not @Defaults.
You cannot use @Default in an ObservableObject. It’s meant to be used in a View.
Toggle
There’s also a SwiftUI.Toggle wrapper that makes it easier to create a toggle based on a Defaults key with a Bool value.
extension Defaults.Keys {
static let showAllDayEvents = Key<Bool>("showAllDayEvents", default: false)
}
struct ShowAllDayEventsSetting: View {
var body: some View {
Defaults.Toggle("Show All-Day Events", key: .showAllDayEvents)
}
}
You can also listen to changes:
struct ShowAllDayEventsSetting: View {
var body: some View {
Defaults.Toggle("Show All-Day Events", key: .showAllDayEvents)
// Note that this has to be directly attached to `Defaults.Toggle`. It's not `View#onChange()`.
.onChange {
print("Value", $0)
}
}
}
Requires at least macOS 11, iOS 14, tvOS 14, watchOS 7.
Observe changes to a key
extension Defaults.Keys {
static let isUnicornMode = Key<Bool>("isUnicornMode", default: false)
}
// …
Task {
for await value in Defaults.updates(.isUnicornMode) {
print("Value:", value)
}
}
In contrast to the native UserDefaults key observation, here you receive a strongly-typed change object.
This works for a Key with an optional too, which will be reset back to nil.
Control propagation of change events
Changes made within the Defaults.withoutPropagation closure will not be propagated to observation callbacks (Defaults.observe() or Defaults.publisher()), and therefore could prevent infinite recursion.
let observer = Defaults.observe(keys: .key1, .key2) {
// …
Defaults.withoutPropagation {
// Update `.key1` without propagating the change to listeners.
Defaults[.key1] = 11
}
// This will be propagated.
Defaults[.someKey] = true
}
let extensionDefaults = UserDefaults(suiteName: "com.unicorn.app")!
extension Defaults.Keys {
static let isUnicorn = Key<Bool>("isUnicorn", default: true, suite: extensionDefaults)
}
Defaults[.isUnicorn]
//=> true
// Or
extensionDefaults[.isUnicorn]
//=> true
Default values are registered with UserDefaults
When you create a Defaults.Key, it automatically registers the default value with normal UserDefaults. This means you can make use of the default value in, for example, bindings in Interface Builder.
Type-erased wrapper for Defaults.Serializable values.
get<Value: Defaults.Serializable>() -> Value?: Retrieve the value which type is Value from UserDefaults.
get<Value: Defaults.Serializable>(_: Value.Type) -> Value?: Specify the Value you want to retrieve. This can be useful in some ambiguous cases.
set<Value: Defaults.Serializable>(_ newValue: Value): Set a new value for Defaults.AnySerializable.
Defaults.reset(keys…)
Type: func
Reset the given keys back to their default values.
You can also specify string keys, which can be useful if you need to store some keys in a collection, as it’s not possible to store Defaults.Key in a collection because it’s generic.
Remove all entries from the given UserDefaults suite.
Defaults.withoutPropagation(_ closure:)
Execute the closure without triggering change events.
Any Defaults key changes made within the closure will not propagate to Defaults event listeners (Defaults.observe() and Defaults.publisher()). This can be useful to prevent infinite recursion when you want to change a key in the callback listening to changes for the same key.
Defaults.migrate(keys..., to: Version)
Defaults.migrate<T: Defaults.Serializable & Codable>(keys..., to: Version)
Defaults.migrate<T: Defaults.NativeType>(keys..., to: Version)
Type: func
Migrate the given keys to the specific version.
@Default(_ key:)
Get/set a Defaults item and also have the SwiftUI view be updated when the value changes.
Advanced
Defaults.CollectionSerializable
public protocol DefaultsCollectionSerializable: Collection, Defaults.Serializable {
init(_ elements: [Element])
}
Type: protocol
A Collection which can store into the native UserDefaults.
It should have an initializer init(_ elements: [Element]) to let Defaults do the de-serialization.
A SetAlgebra which can store into the native UserDefaults.
It should have a function func toArray() -> [Element] to let Defaults do the serialization.
Advanced usage
Custom types
Although Defaults already has built-in support for many types, you might need to be able to use your own custom type. The below guide will show you how to make your own custom type work with Defaults.
Create your own custom type.
struct User {
let name: String
let age: String
}
Create a bridge that conforms to Defaults.Bridge, which is responsible for handling serialization and deserialization.
struct UserBridge: Defaults.Bridge {
typealias Value = User
typealias Serializable = [String: String]
public func serialize(_ value: Value?) -> Serializable? {
guard let value else {
return nil
}
return [
"name": value.name,
"age": value.age
]
}
public func deserialize(_ object: Serializable?) -> Value? {
guard
let object,
let name = object["name"],
let age = object["age"]
else {
return nil
}
return User(
name: name,
age: age
)
}
}
Create an extension of User that conforms to Defaults.Serializable. Its static bridge should be the bridge we created above.
struct User {
let name: String
let age: String
}
extension User: Defaults.Serializable {
static let bridge = UserBridge()
}
There might be situations where you want to use [String: Any] directly, but Defaults need its values to conform to Defaults.Serializable. The type-eraser Defaults.AnySerializable helps overcome this limitation.
Defaults.AnySerializable is only available for values that conform to Defaults.Serializable.
Warning: The type-eraser should only be used when there’s no other way to handle it because it has much worse performance. It should only be used in wrapped types. For example, wrapped in Array, Set or Dictionary.
Primitive type
Defaults.AnySerializable conforms to ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByBooleanLiteral, ExpressibleByNilLiteral, ExpressibleByArrayLiteral, and ExpressibleByDictionaryLiteral.
Which means you can assign these primitive types directly:
let any = Defaults.Key<Defaults.AnySerializable>("anyKey", default: 1)
Defaults[any] = "🦄"
Other types
Using get and set
For other types, you will have to assign it like this:
enum mime: String, Defaults.Serializable {
case JSON = "application/json"
case STREAM = "application/octet-stream"
}
let any = Defaults.Key<Defaults.AnySerializable>("anyKey", default: [Defaults.AnySerializable(mime.JSON)])
if let mimeType: mime = Defaults[any].get() {
print(mimeType.rawValue)
//=> "application/json"
}
Defaults[any].set(mime.STREAM)
if let mimeType: mime = Defaults[any].get() {
print(mimeType.rawValue)
//=> "application/octet-stream"
}
Wrapped in Array, Set, or Dictionary
Defaults.AnySerializable also support the above types wrapped in Array, Set, Dictionary.
Here is the example for [String: Defaults.AnySerializable]:
extension Defaults.Keys {
static let magic = Key<[String: Defaults.AnySerializable]>("magic", default: [:])
}
enum mime: String, Defaults.Serializable {
case JSON = "application/json"
}
// …
Defaults[.magic]["unicorn"] = "🦄"
if let value: String = Defaults[.magic]["unicorn"]?.get() {
print(value)
//=> "🦄"
}
Defaults[.magic]["number"] = 3
Defaults[.magic]["boolean"] = true
Defaults[.magic]["enum"] = Defaults.AnySerializable(mime.JSON)
if let mimeType: mime = Defaults[.magic]["enum"]?.get() {
print(mimeType.rawValue)
//=> "application/json"
}
You may have a type that conforms to Codable & NSSecureCoding or a Codable & RawRepresentable enum. By default, Defaults will prefer the Codable conformance and use the CodableBridge to serialize it into a JSON string. If you want to serialize it as a NSSecureCoding data or use the raw value of the RawRepresentable enum, you can conform to Defaults.PreferNSSecureCoding or Defaults.PreferRawRepresentable to override the default bridge:
Had we not added Defaults.PreferRawRepresentable, the stored representation would have been "application/json" instead of application/json.
This can also be useful if you conform a type you don’t control to Defaults.Serializable as the type could receive Codable conformance at any time and then the stored representation would change, which could make the value unreadable. By explicitly defining which bridge to use, you ensure the stored representation will always stay the same.
Custom Collection type
Create your Collection and make its elements conform to Defaults.Serializable.
struct Bag<Element: Defaults.Serializable>: Collection {
var items: [Element]
var startIndex: Int { items.startIndex }
var endIndex: Int { items.endIndex }
mutating func insert(element: Element, at: Int) {
items.insert(element, at: at)
}
func index(after index: Int) -> Int {
items.index(after: index)
}
subscript(position: Int) -> Element {
items[position]
}
}
Create an extension of Bag that conforms to Defaults.CollectionSerializable.
After Defaults v5, you don’t need to use Codable to store dictionary, Defaults supports storing dictionary natively.
For Defaults support types, see Support types.
It’s inspired by that package and other solutions. The main difference is that this module doesn’t hardcode the default values and comes with Codable support.
Defaults
Store key-value pairs persistently across launches of your app.
It uses
UserDefaultsunderneath but exposes a type-safe facade with lots of nice conveniences.It’s used in production by all my apps (1 million+ users).
Highlights
UserDefaultsvalue changes.Benefits over
@AppStorageCodable.Togglecomponent.Compatibility
Install
Add
https://github.com/sindresorhus/Defaultsin the “Swift Package Manager” tab in Xcode.Requires Xcode 14.1 or later
Support types
Int(8/16/32/64)UInt(8/16/32/64)DoubleCGFloatFloatStringBoolDateDataURLUUIDNSColor(macOS)UIColor(iOS)Color[^1] (SwiftUI)CodableNSSecureCodingRange,ClosedRangeDefaults also support the above types wrapped in
Array,Set,Dictionary,Range,ClosedRange, and even wrapped in nested types. For example,[[String: Set<[String: Int]>]].For more types, see the enum example,
Codableexample, or advanced Usage. For more examples, see Tests/DefaultsTests.You can easily add support for any custom type.
If a type conforms to both
NSSecureCodingandCodable, thenCodablewill be used for the serialization.[^1]: You cannot use
Color.accentColor.Usage
API documentation.
You declare the defaults keys upfront with a type and default value.
The key name must be ASCII, not start with
@, and cannot contain a dot (.).You can then access it as a subscript on the
Defaultsglobal:You can also declare optional keys for when you don’t want to declare a default value upfront:
The default value is then
nil.You can also specify a dynamic default value. This can be useful when the default value may change during the lifetime of the app:
Enum example
(This works as long as the raw value of the enum is any of the supported types)
Codable example
Use keys directly
You are not required to attach keys to
Defaults.Keys.SwiftUI support
@DefaultYou can use the
@Defaultproperty wrapper to get/set aDefaultsitem and also have the view be updated when the value changes. This is similar to@State.Note that it’s
@Default, not@Defaults.You cannot use
@Defaultin anObservableObject. It’s meant to be used in aView.ToggleThere’s also a
SwiftUI.Togglewrapper that makes it easier to create a toggle based on aDefaultskey with aBoolvalue.You can also listen to changes:
Requires at least macOS 11, iOS 14, tvOS 14, watchOS 7.
Observe changes to a key
In contrast to the native
UserDefaultskey observation, here you receive a strongly-typed change object.Reset keys to their default values
This works for a
Keywith an optional too, which will be reset back tonil.Control propagation of change events
Changes made within the
Defaults.withoutPropagationclosure will not be propagated to observation callbacks (Defaults.observe()orDefaults.publisher()), and therefore could prevent infinite recursion.It’s just
UserDefaultswith sugarThis works too:
Shared
UserDefaultsDefault values are registered with
UserDefaultsWhen you create a
Defaults.Key, it automatically registers thedefaultvalue with normalUserDefaults. This means you can make use of the default value in, for example, bindings in Interface Builder.API
DefaultsDefaults.KeysType:
classStores the keys.
Defaults.Key(aliasDefaults.Keys.Key)Type:
classCreate a key with a default value.
The default value is written to the actual
UserDefaultsand can be used elsewhere. For example, with a Interface Builder binding.Defaults.SerializableType:
protocolTypes that conform to this protocol can be used with
Defaults.The type should have a static variable
bridgewhich should reference an instance of a type that conforms toDefaults.Bridge.Defaults.BridgeType:
protocolA
Bridgeis responsible for serialization and deserialization.It has two associated types
ValueandSerializable.Value: The type you want to use.Serializable: The type stored inUserDefaults.serialize: Executed before storing to theUserDefaults.deserialize: Executed after retrieving its value from theUserDefaults.Defaults.AnySerializableType:
classType-erased wrapper for
Defaults.Serializablevalues.get<Value: Defaults.Serializable>() -> Value?: Retrieve the value which type isValuefrom UserDefaults.get<Value: Defaults.Serializable>(_: Value.Type) -> Value?: Specify theValueyou want to retrieve. This can be useful in some ambiguous cases.set<Value: Defaults.Serializable>(_ newValue: Value): Set a new value forDefaults.AnySerializable.Defaults.reset(keys…)Type:
funcReset the given keys back to their default values.
You can also specify string keys, which can be useful if you need to store some keys in a collection, as it’s not possible to store
Defaults.Keyin a collection because it’s generic.Defaults.removeAllType:
funcRemove all entries from the given
UserDefaultssuite.Defaults.withoutPropagation(_ closure:)Execute the closure without triggering change events.
Any
Defaultskey changes made within the closure will not propagate toDefaultsevent listeners (Defaults.observe()andDefaults.publisher()). This can be useful to prevent infinite recursion when you want to change a key in the callback listening to changes for the same key.Defaults.migrate(keys..., to: Version)Type:
funcMigrate the given keys to the specific version.
@Default(_ key:)Get/set a
Defaultsitem and also have the SwiftUI view be updated when the value changes.Advanced
Defaults.CollectionSerializableType:
protocolA
Collectionwhich can store into the nativeUserDefaults.It should have an initializer
init(_ elements: [Element])to letDefaultsdo the de-serialization.Defaults.SetAlgebraSerializableType:
protocolA
SetAlgebrawhich can store into the nativeUserDefaults.It should have a function
func toArray() -> [Element]to letDefaultsdo the serialization.Advanced usage
Custom types
Although
Defaultsalready has built-in support for many types, you might need to be able to use your own custom type. The below guide will show you how to make your own custom type work withDefaults.Defaults.Bridge, which is responsible for handling serialization and deserialization.Userthat conforms toDefaults.Serializable. Its static bridge should be the bridge we created above.Dynamic value
There might be situations where you want to use
[String: Any]directly, butDefaultsneed its values to conform toDefaults.Serializable. The type-eraserDefaults.AnySerializablehelps overcome this limitation.Defaults.AnySerializableis only available for values that conform toDefaults.Serializable.Warning: The type-eraser should only be used when there’s no other way to handle it because it has much worse performance. It should only be used in wrapped types. For example, wrapped in
Array,SetorDictionary.Primitive type
Defaults.AnySerializableconforms toExpressibleByStringLiteral,ExpressibleByIntegerLiteral,ExpressibleByFloatLiteral,ExpressibleByBooleanLiteral,ExpressibleByNilLiteral,ExpressibleByArrayLiteral, andExpressibleByDictionaryLiteral.Which means you can assign these primitive types directly:
Other types
Using
getandsetFor other types, you will have to assign it like this:
Wrapped in
Array,Set, orDictionaryDefaults.AnySerializablealso support the above types wrapped inArray,Set,Dictionary.Here is the example for
[String: Defaults.AnySerializable]:For more examples, see Tests/DefaultsAnySerializableTests.
Serialization for ambiguous
CodabletypeYou may have a type that conforms to
Codable & NSSecureCodingor aCodable & RawRepresentableenum. By default,Defaultswill prefer theCodableconformance and use theCodableBridgeto serialize it into a JSON string. If you want to serialize it as aNSSecureCodingdata or use the raw value of theRawRepresentableenum, you can conform toDefaults.PreferNSSecureCodingorDefaults.PreferRawRepresentableto override the default bridge:Had we not added
Defaults.PreferRawRepresentable, the stored representation would have been"application/json"instead ofapplication/json.This can also be useful if you conform a type you don’t control to
Defaults.Serializableas the type could receiveCodableconformance at any time and then the stored representation would change, which could make the value unreadable. By explicitly defining which bridge to use, you ensure the stored representation will always stay the same.Custom
CollectiontypeCollectionand make its elements conform toDefaults.Serializable.Bagthat conforms toDefaults.CollectionSerializable.Custom
SetAlgebratypeSetAlgebraand make its elements conform toDefaults.Serializable & HashableSetBagthat conforms toDefaults.SetAlgebraSerializableFAQ
How can I store a dictionary of arbitrary values?
After
Defaultsv5, you don’t need to useCodableto store dictionary,Defaultssupports storing dictionary natively. ForDefaultssupport types, see Support types.How is this different from
SwiftyUserDefaults?It’s inspired by that package and other solutions. The main difference is that this module doesn’t hardcode the default values and comes with Codable support.
Maintainers
Former
Related