2018-04-12 01:19:30 +08:00
# Defaults [![Build Status](https://travis-ci.org/sindresorhus/Defaults.svg?branch=master)](https://travis-ci.org/sindresorhus/Defaults)
> Swifty and modern [UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults)
2020-04-18 14:31:06 +08:00
Store key-value pairs persistently across launches of your app.
2020-01-21 01:07:30 +08:00
2020-01-09 18:39:31 +08:00
It uses `NSUserDefaults` underneath but exposes a type-safe facade with lots of nice conveniences.
2018-10-18 15:16:37 +08:00
2020-01-09 18:39:31 +08:00
It's used in production by apps like [Gifski ](https://github.com/sindresorhus/Gifski ), [Dato ](https://sindresorhus.com/dato ), [Lungo ](https://sindresorhus.com/lungo ), [Battery Indicator ](https://sindresorhus.com/battery-indicator ), and [HEIC Converter ](https://sindresorhus.com/heic-converter ).
2018-04-12 01:19:30 +08:00
2020-05-21 13:04:15 +08:00
For a real-world example, see my [Plash app ](https://github.com/sindresorhus/Plash/blob/533dbc888d8ba3bd9581e60320af282a22c53f85/Plash/Constants.swift#L9-L18 ).
2018-04-12 01:19:30 +08:00
## Highlights
- **Strongly typed:** You declare the type and default value upfront.
- **Codable support:** You can store any [Codable ](https://developer.apple.com/documentation/swift/codable ) value, like an enum.
2019-10-30 19:57:31 +08:00
- **NSSecureCoding support:** You can store any [NSSecureCoding ](https://developer.apple.com/documentation/foundation/nssecurecoding ) value.
2020-04-18 15:25:39 +08:00
- **SwiftUI:** Property wrapper that updates the view when the `UserDefaults` value changes.
2020-01-21 00:41:13 +08:00
- **Publishers:** Combine publishers built-in.
2020-04-18 15:25:39 +08:00
- **Observation:** Observe changes to keys.
- **Debuggable:** The data is stored as JSON-serialized values.
2018-04-12 01:19:30 +08:00
2018-04-16 17:19:45 +08:00
## Compatibility
2018-04-12 01:19:30 +08:00
- macOS 10.12+
2018-04-16 17:19:45 +08:00
- iOS 10+
- tvOS 10+
- watchOS 3+
2018-04-12 01:19:30 +08:00
## Install
2020-04-18 14:31:06 +08:00
#### Swift Package Manager
2018-04-12 01:19:30 +08:00
2020-05-18 13:01:16 +08:00
Add `https://github.com/sindresorhus/Defaults` in the [“Swift Package Manager” tab in Xcode ](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app ).
2018-04-12 01:19:30 +08:00
2020-05-18 13:01:16 +08:00
You also need to set the build setting “Other Linker Flags” to `-weak_framework Combine` to work around [this Xcode bug ](https://github.com/feedback-assistant/reports/issues/44 ).
2020-04-18 14:31:06 +08:00
2018-06-07 12:07:48 +08:00
#### Carthage
2018-04-12 01:19:30 +08:00
```
github "sindresorhus/Defaults"
```
2018-06-07 12:07:48 +08:00
#### CocoaPods
2018-06-29 16:49:06 +08:00
```ruby
2018-06-07 12:07:48 +08:00
pod 'Defaults'
```
2018-04-12 01:19:30 +08:00
## Usage
You declare the defaults keys upfront with type and default value.
```swift
import Cocoa
import Defaults
extension Defaults.Keys {
2018-10-17 18:22:10 +08:00
static let quality = Key< Double > ("quality", default: 0.8)
// ^ ^ ^ ^
// Key Type UserDefaults name Default value
2018-04-12 01:19:30 +08:00
}
```
2019-09-11 12:59:28 +08:00
You can then access it as a subscript on the `Defaults` global:
2018-04-12 01:19:30 +08:00
```swift
2019-09-11 12:59:28 +08:00
Defaults[.quality]
2018-04-12 01:19:30 +08:00
//=> 0.8
2019-09-11 12:59:28 +08:00
Defaults[.quality] = 0.5
2018-04-12 01:19:30 +08:00
//=> 0.5
2019-09-11 12:59:28 +08:00
Defaults[.quality] += 0.1
2018-04-12 01:19:30 +08:00
//=> 0.6
2019-09-11 12:59:28 +08:00
Defaults[.quality] = "🦄"
2018-04-12 01:19:30 +08:00
//=> [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:
```swift
extension Defaults.Keys {
2020-01-21 15:29:57 +08:00
static let name = Key< Double ? > ("name")
2018-04-12 01:19:30 +08:00
}
2019-09-11 12:59:28 +08:00
if let name = Defaults[.name] {
2018-04-12 01:19:30 +08:00
print(name)
}
```
2019-08-15 18:48:10 +08:00
The default value is then `nil` .
2019-10-30 19:57:31 +08:00
---
If you have `NSSecureCoding` classes which you want to save, you can use them as follows:
```swift
extension Defaults.Keys {
static let someSecureCoding = NSSecureCodingKey< SomeNSSecureCodingClass > ("someSecureCoding", default: SomeNSSecureCodingClass(string: "Default", int: 5, bool: true))
static let someOptionalSecureCoding = NSSecureCodingOptionalKey< Double > ("someOptionalSecureCoding")
}
Defaults[.someSecureCoding].string
//=> "Default"
Defaults[.someSecureCoding].int
//=> 5
Defaults[.someSecureCoding].bool
//=> true
```
You can use those keys just like in all the other examples. The return value will be your `NSSecureCoding` class.
2018-04-12 01:19:30 +08:00
### Enum example
```swift
enum DurationKeys: String, Codable {
case tenMinutes = "10 Minutes"
case halfHour = "30 Minutes"
case oneHour = "1 Hour"
}
extension Defaults.Keys {
2018-10-17 18:22:10 +08:00
static let defaultDuration = Key< DurationKeys > ("defaultDuration", default: .oneHour)
2018-04-12 01:19:30 +08:00
}
2019-09-11 12:59:28 +08:00
Defaults[.defaultDuration].rawValue
2018-04-12 01:19:30 +08:00
//=> "1 Hour"
```
2018-10-17 18:22:10 +08:00
### Use keys directly
You are not required to attach keys to `Defaults.Keys` .
```swift
let isUnicorn = Defaults.Key< Bool > ("isUnicorn", default: true)
2019-09-11 12:59:28 +08:00
Defaults[isUnicorn]
2018-10-17 18:22:10 +08:00
//=> true
```
2020-04-18 15:25:39 +08:00
### SwiftUI support
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` .
```swift
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 Unicorn", isOn: $hasUnicorn)
}
}
```
Note that it's `@Default` , not `@Defaults` .
2020-05-21 13:04:15 +08:00
You cannot use `@Default` in an `ObservableObject` . It's meant to be used in a `View` .
2020-04-18 15:25:39 +08:00
This is only implemented for `Defaults.Key` . PR welcome for `Defaults.NSSecureCoding` if you need it.
2018-10-17 18:22:10 +08:00
### Observe changes to a key
```swift
extension Defaults.Keys {
static let isUnicornMode = Key< Bool > ("isUnicornMode", default: false)
}
2019-09-11 12:59:28 +08:00
let observer = Defaults.observe(.isUnicornMode) { change in
2018-10-17 18:22:10 +08:00
// Initial event
print(change.oldValue)
//=> false
print(change.newValue)
//=> false
// First actual event
print(change.oldValue)
//=> false
print(change.newValue)
//=> true
}
2019-09-11 12:59:28 +08:00
Defaults[.isUnicornMode] = true
2018-10-17 18:22:10 +08:00
```
2019-05-09 19:08:18 +08:00
In contrast to the native `UserDefaults` key observation, here you receive a strongly-typed change object.
2020-01-21 00:41:13 +08:00
There is also an observation API using the [Combine ](https://developer.apple.com/documentation/combine ) framework, exposing a [Publisher ](https://developer.apple.com/documentation/combine/publisher ) for key changes:
```swift
let publisher = Defaults.publisher(.isUnicornMode)
let cancellable = publisher.sink { change in
// Initial event
print(change.oldValue)
//=> false
print(change.newValue)
//=> false
// First actual event
print(change.oldValue)
//=> false
print(change.newValue)
//=> true
}
Defaults[.isUnicornMode] = true
// To invalidate the observation.
cancellable.cancel()
```
2019-10-30 19:50:24 +08:00
### Invalidate observations automatically
```swift
extension Defaults.Keys {
static let isUnicornMode = Key< Bool > ("isUnicornMode", default: false)
}
final class Foo {
init() {
Defaults.observe(.isUnicornMode) { change in
print(change.oldValue)
print(change.newValue)
}.tieToLifetime(of: self)
}
}
Defaults[.isUnicornMode] = true
```
The observation will be valid until `self` is deinitialized.
2019-09-11 15:09:12 +08:00
### Reset keys to their default values
```swift
extension Defaults.Keys {
static let isUnicornMode = Key< Bool > ("isUnicornMode", default: false)
}
2019-09-11 12:59:28 +08:00
Defaults[.isUnicornMode] = true
2019-09-11 15:09:12 +08:00
//=> true
2019-09-11 12:59:28 +08:00
Defaults.reset(.isUnicornMode)
2019-09-11 15:09:12 +08:00
2019-09-11 12:59:28 +08:00
Defaults[.isUnicornMode]
2019-09-11 15:09:12 +08:00
//=> false
```
2020-01-21 15:29:57 +08:00
This works for a `Key` with an optional too, which will be reset back to `nil` .
2019-09-11 15:09:12 +08:00
2020-08-29 04:38:56 +08:00
### 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.
```swift
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
}
```
2019-09-11 15:56:11 +08:00
### It's just `UserDefaults` with sugar
This works too:
```swift
extension Defaults.Keys {
static let isUnicorn = Key< Bool > ("isUnicorn", default: true)
}
UserDefaults.standard[.isUnicorn]
//=> true
```
### Shared `UserDefaults`
```swift
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`
2018-10-17 18:22:10 +08:00
2019-09-11 15:56:11 +08:00
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.
2018-10-17 18:22:10 +08:00
```swift
extension Defaults.Keys {
static let isUnicornMode = Key< Bool > ("isUnicornMode", default: true)
}
print(UserDefaults.standard.bool(forKey: isUnicornMode.name))
//=> true
```
2018-04-12 01:19:30 +08:00
## API
2019-09-11 12:59:28 +08:00
### `Defaults`
2018-04-12 01:19:30 +08:00
2018-10-17 18:22:10 +08:00
#### `Defaults.Keys`
2018-04-12 01:19:30 +08:00
Type: `class`
Stores the keys.
2018-10-17 18:22:10 +08:00
#### `Defaults.Key` *(alias `Defaults.Keys.Key`)*
```swift
Defaults.Key< T > (_ key: String, default: T, suite: UserDefaults = .standard)
```
2018-04-12 01:19:30 +08:00
Type: `class`
Create a key with a default value.
2019-09-11 12:59:28 +08:00
The default value is written to the actual `UserDefaults` and can be used elsewhere. For example, with a Interface Builder binding.
2018-10-17 18:22:10 +08:00
2019-10-30 19:57:31 +08:00
#### `Defaults.NSSecureCodingKey` *(alias `Defaults.Keys.NSSecureCodingKey`)*
```swift
Defaults.NSSecureCodingKey< T > (_ key: String, default: T, suite: UserDefaults = .standard)
```
Type: `class`
Create a NSSecureCoding 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.NSSecureCodingOptionalKey` *(alias `Defaults.Keys.NSSecureCodingOptionalKey`)*
```swift
Defaults.NSSecureCodingOptionalKey< T > (_ key: String, suite: UserDefaults = .standard)
```
Type: `class`
Create a NSSecureCoding key with an optional value.
2020-04-18 14:19:38 +08:00
#### `Defaults.reset(keys…)`
2018-04-12 01:19:30 +08:00
Type: `func`
2019-09-11 12:59:28 +08:00
Reset the given keys back to their default values.
2018-04-12 01:19:30 +08:00
2020-04-17 22:32:44 +08:00
You can specify up to 10 keys. If you need to specify more, call this method multiple times.
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.
2019-09-11 12:59:28 +08:00
#### `Defaults.observe`
2018-10-17 18:22:10 +08:00
```swift
2019-09-11 12:59:28 +08:00
Defaults.observe< T: Codable > (
2018-10-17 18:22:10 +08:00
_ key: Defaults.Key< T > ,
2020-04-13 13:14:55 +08:00
options: ObservationOptions = [.initial],
2018-10-17 18:22:10 +08:00
handler: @escaping (KeyChange< T > ) -> Void
2020-04-13 12:31:54 +08:00
) -> Defaults.Observation
2018-10-17 18:22:10 +08:00
```
2019-10-30 19:57:31 +08:00
```swift
2020-01-21 00:41:13 +08:00
Defaults.observe< T: NSSecureCoding > (
2019-10-30 19:57:31 +08:00
_ key: Defaults.NSSecureCodingKey< T > ,
2020-04-13 13:14:55 +08:00
options: ObservationOptions = [.initial],
2019-10-30 19:57:31 +08:00
handler: @escaping (NSSecureCodingKeyChange< T > ) -> Void
2020-04-13 12:31:54 +08:00
) -> Defaults.Observation
2019-10-30 19:57:31 +08:00
```
```swift
2020-01-21 00:41:13 +08:00
Defaults.observe< T: NSSecureCoding > (
2019-10-30 19:57:31 +08:00
_ key: Defaults.NSSecureCodingOptionalKey< T > ,
2020-04-13 13:14:55 +08:00
options: ObservationOptions = [.initial],
2019-10-30 19:57:31 +08:00
handler: @escaping (NSSecureCodingOptionalKeyChange< T > ) -> Void
2020-04-13 12:31:54 +08:00
) -> Defaults.Observation
2019-10-30 19:57:31 +08:00
```
2018-10-17 18:22:10 +08:00
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.
2020-08-29 04:12:29 +08:00
#### `Defaults.observe(keys: keys..., options:)`
Type: `func`
2020-08-29 04:38:56 +08:00
Observe multiple keys of any type, but without any information about the changes.
2020-08-29 04:12:29 +08:00
2020-08-29 04:38:56 +08:00
Options are the same as in `.observe(…)` for a single key.
2020-08-29 04:12:29 +08:00
2020-04-18 14:19:38 +08:00
#### `Defaults.publisher(_ key:, options:)`
2020-01-21 00:41:13 +08:00
```swift
Defaults.publisher< T: Codable > (
_ key: Defaults.Key< T > ,
2020-04-13 13:14:55 +08:00
options: ObservationOptions = [.initial]
2020-01-21 00:41:13 +08:00
) -> AnyPublisher< KeyChange < T > , Never>
```
```swift
Defaults.publisher< T: NSSecureCoding > (
_ key: Defaults.NSSecureCodingKey< T > ,
2020-04-13 13:14:55 +08:00
options: ObservationOptions = [.initial]
2020-01-21 00:41:13 +08:00
) -> AnyPublisher< NSSecureCodingKeyChange < T > , Never>
```
```swift
Defaults.publisher< T: NSSecureCoding > (
_ key: Defaults.NSSecureCodingOptionalKey< T > ,
2020-04-13 13:14:55 +08:00
options: ObservationOptions = [.initial]
2020-01-21 00:41:13 +08:00
) -> AnyPublisher< NSSecureCodingOptionalKeyChange < T > , Never>
```
Type: `func`
Observation API using [Publisher ](https://developer.apple.com/documentation/combine/publisher ) from the [Combine ](https://developer.apple.com/documentation/combine ) framework.
Available on macOS 10.15+, iOS 13.0+, tvOS 13.0+, and watchOS 6.0+.
2020-04-18 14:19:38 +08:00
#### `Defaults.publisher(keys: keys…, options:)`
2020-01-21 00:41:13 +08:00
Type: `func`
[Combine ](https://developer.apple.com/documentation/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+.
2019-09-11 15:32:18 +08:00
#### `Defaults.removeAll`
2019-09-11 12:59:28 +08:00
```swift
2019-09-11 15:32:18 +08:00
Defaults.removeAll(suite: UserDefaults = .standard)
2019-09-11 12:59:28 +08:00
```
Type: `func`
2020-04-17 22:32:44 +08:00
Remove all entries from the given `UserDefaults` suite.
2019-09-11 12:59:28 +08:00
2020-04-13 12:31:54 +08:00
### `Defaults.Observation`
2019-10-30 19:50:24 +08:00
Type: `protocol`
Represents an observation of a defaults key.
2020-04-13 12:31:54 +08:00
#### `Defaults.Observation#invalidate`
2019-10-30 19:50:24 +08:00
```swift
2020-04-13 12:31:54 +08:00
Defaults.Observation#invalidate()
2019-10-30 19:50:24 +08:00
```
Type: `func`
Invalidate the observation.
2020-04-13 12:31:54 +08:00
#### `Defaults.Observation#tieToLifetime`
2019-10-30 19:50:24 +08:00
```swift
@discardableResult
2020-04-13 12:31:54 +08:00
Defaults.Observation#tieToLifetime(of weaklyHeldObject: AnyObject) -> Self
2019-10-30 19:50:24 +08:00
```
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.
2020-04-13 12:31:54 +08:00
#### `Defaults.Observation.removeLifetimeTie`
2019-10-30 19:50:24 +08:00
```swift
2020-04-13 12:31:54 +08:00
Defaults.Observation#removeLifetimeTie()
2019-10-30 19:50:24 +08:00
```
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.
2020-08-29 04:38:56 +08:00
#### `Defaults.withoutPropagation(_ closure:)`
2020-08-29 04:12:29 +08:00
2020-08-29 04:38:56 +08:00
Execute the closure without triggering change events.
2020-08-29 04:12:29 +08:00
2020-08-29 04:38:56 +08:00
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.
2020-08-29 04:12:29 +08:00
2020-04-18 15:25:39 +08:00
### `@Default(_ key:)`
Get/set a `Defaults` item and also have the view be updated when the value changes.
This is only implemented for `Defaults.Key` . PR welcome for `Defaults.NSSecureCoding` if you need it.
2018-04-12 01:19:30 +08:00
## FAQ
2020-04-13 13:39:25 +08:00
### How can I store a dictionary of arbitrary values?
You cannot store `[String: Any]` directly as it cannot conform to `Codable` . However, you can use the [`AnyCodable` ](https://github.com/Flight-School/AnyCodable ) package to work around this `Codable` limitation:
```swift
import AnyCodable
extension Defaults.Keys {
static let magic = Key< [String: AnyCodable]>("magic", default: [:])
}
// …
Defaults[.magic]["unicorn"] = "🦄"
if let value = Defaults[.magic]["unicorn"]?.value {
print(value)
//=> "🦄"
}
Defaults[.magic]["number"] = 3
Defaults[.magic]["boolean"] = true
```
2018-04-12 01:19:30 +08:00
### How is this different from [`SwiftyUserDefaults`](https://github.com/radex/SwiftyUserDefaults)?
2018-10-17 18:22:10 +08:00
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.
2018-04-12 01:19:30 +08:00
2020-08-29 07:57:07 +08:00
## Maintainers
- [Sindre Sorhus ](https://github.com/sindresorhus )
- [Kacper Rączy ](https://github.com/fredyshox )
2018-04-12 01:19:30 +08:00
## Related
2020-05-07 23:27:59 +08:00
- [Preferences ](https://github.com/sindresorhus/Preferences ) - Add a preferences window to your macOS app
- [KeyboardShortcuts ](https://github.com/sindresorhus/KeyboardShortcuts ) - Add user-customizable global keyboard shortcuts to your macOS app
2018-04-12 01:19:30 +08:00
- [LaunchAtLogin ](https://github.com/sindresorhus/LaunchAtLogin ) - Add "Launch at Login" functionality to your macOS app
- [DockProgress ](https://github.com/sindresorhus/DockProgress ) - Show progress in your app's Dock icon
2019-07-08 15:07:59 +08:00
- [Gifski ](https://github.com/sindresorhus/Gifski ) - Convert videos to high-quality GIFs on your Mac
2018-10-11 02:24:30 +08:00
- [More… ](https://github.com/search?q=user%3Asindresorhus+language%3Aswift )