Defaults
Swifty and modern UserDefaults
Store key-value pairs persistently across launches of your app.
It uses NSUserDefaults
underneath but exposes a type-safe facade with lots of nice conveniences.
It's used in production by apps like Gifski, Dato, Lungo, Battery Indicator, and HEIC Converter.
For a real-world example, see the Plash app.
Highlights
- Strongly typed: You declare the type and default value upfront.
- Codable support: You can store any Codable value, like an enum.
- NSSecureCoding support: You can store any NSSecureCoding value.
- SwiftUI: Property wrapper that updates the view when the
UserDefaults
value changes. - Publishers: Combine publishers built-in.
- Observation: Observe changes to keys.
- Debuggable: The data is stored as JSON-serialized values.
- Customizable: You can serialize and deserialize your own type in your own way.
Compatibility
- macOS 10.13+
- iOS 12+
- tvOS 12+
- watchOS 5+
Sindre‘s open source work is supported by the community
Special thanks to:Migration Guides
From v4 to v5
Install
Add https://github.com/sindresorhus/Defaults
in the “Swift Package Manager” tab in Xcode.
Support types
Int(8/16/32/64)
UInt(8/16/32/64)
Double
CGFloat
Float
String
Bool
Date
Data
URL
NSColor
(macOS)UIColor
(iOS)Color
(SwiftUI)Codable
NSSecureCoding
Defaults also support the above types wrapped in Array
, Set
, Dictionary
, and even wrapped in nested types. For example, [[String: Set<[String: Int]>]]
.
For more types, see the enum example, Codable
example, or advanced Usage. For more examples, see Tests/DefaultsTests.
You can easily add support for any custom type.
If a type conforms to both NSSecureCoding
and Codable
, then Codable
will be used for the serialization.
Usage
You declare the defaults keys upfront with type and default value.
You can then access it as a subscript on the Defaults
global:
You can also declare optional keys for when you don't want to declare a default value upfront:
The default value is then nil
.
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
@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
.
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.
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 UserDefaults
key observation, here you receive a strongly-typed change object.
There is also an observation API using the Combine framework, exposing a Publisher for key changes:
Invalidate observations automatically
The observation will be valid until self
is deinitialized.
Reset keys to their default values
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.
It's just UserDefaults
with sugar
This works too:
Shared UserDefaults
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.
API
Defaults
Defaults.Keys
Type: class
Stores the keys.
Defaults.Key
(alias Defaults.Keys.Key
)
Type: class
Create a key with a default value.
The default value is written to the actual UserDefaults
and can be used elsewhere. For example, with a Interface Builder binding.
Defaults.Serializable
Type: protocol
Types that conform to this protocol can be used with Defaults
.
The type should have a static variable bridge
which should reference an instance of a type that conforms to Defaults.Bridge
.
Defaults.Bridge
Type: protocol
A Bridge
is responsible for serialization and deserialization.
It has two associated types Value
and Serializable
.
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.AnySerializable
Type: class
Type-erased wrapper for Defaults.Serializable
values.
get<Value: Defaults.Serializable>() -> Value?
: Retrieve the value which type isValue
from UserDefaults.get<Value: Defaults.Serializable>(_: Value.Type) -> Value?
: Specify theValue
you 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: 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.
Defaults.observe
Type: func
Observe changes to a key or an optional key.
By default, it will also trigger an initial event on creation. This can be useful for setting default values on controls. You can override this behavior with the options
argument.
Defaults.observe(keys: keys..., options:)
Type: func
Observe multiple keys of any type, but without any information about the changes.
Options are the same as in .observe(…)
for a single key.
Defaults.publisher(_ key:, options:)
Type: func
Observation API using Publisher from the Combine framework.
Available on macOS 10.15+, iOS 13.0+, tvOS 13.0+, and watchOS 6.0+.
Defaults.publisher(keys: keys…, options:)
Type: func
Combine observation API for multiple key observation, but without specific information about changes.
Available on macOS 10.15+, iOS 13.0+, tvOS 13.0+, and watchOS 6.0+.
Defaults.removeAll
Type: func
Remove all entries from the given UserDefaults
suite.
Defaults.Observation
Type: protocol
Represents an observation of a defaults key.
Defaults.Observation#invalidate
Type: func
Invalidate the observation.
Defaults.Observation#tieToLifetime
Type: func
Keep the observation alive for as long as, and no longer than, another object exists.
When weaklyHeldObject
is deinitialized, the observation is invalidated automatically.
Defaults.Observation.removeLifetimeTie
Type: func
Break the lifetime tie created by tieToLifetime(of:)
, if one exists.
The effects of any call to tieToLifetime(of:)
are reversed. Note however that if the tied-to object has already died, then the observation is already invalid and this method has no logical effect.
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)
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
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.
Defaults.SetAlgebraSerializable
Type: protocol
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.
- Create a bridge that conforms to
Defaults.Bridge
, which is responsible for handling serialization and deserialization.
- Create an extension of
User
that conforms toDefaults.Serializable
. Its static bridge should be the bridge we created above.
- Create some keys and enjoy it.
Dynamic value
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:
Other types
Using get
and set
For other types, you will have to assign it like this:
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]
:
For more examples, see Tests/DefaultsAnySerializableTests.
Serialization for ambiguous Codable
type
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 toDefaults.Serializable
.
- Create an extension of
Bag
that conforms toDefaults.CollectionSerializable
.
- Create some keys and enjoy it.
Custom SetAlgebra
type
- Create your
SetAlgebra
and make its elements conform toDefaults.Serializable & Hashable
- Create an extension of
SetBag
that conforms toDefaults.SetAlgebraSerializable
- Create some keys and enjoy it.
FAQ
How can I store a dictionary of arbitrary values?
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.
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
Related
- Preferences - Add a preferences window to your macOS app
- KeyboardShortcuts - Add user-customizable global keyboard shortcuts to your macOS app
- LaunchAtLogin - Add "Launch at Login" functionality to your macOS app
- Regex - Swifty regular expressions
- DockProgress - Show progress in your app's Dock icon
- Gifski - Convert videos to high-quality GIFs on your Mac
- More…