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)
2018-10-18 15:16:37 +08:00
This package is used in production by the [Lungo ](https://sindresorhus.com/lungo ), [Battery Indicator ](https://sindresorhus.com/battery-indicator ), and [HEIC Converter ](https://sindresorhus.com/heic-converter ) app.
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.
- **Debuggable:** The data is stored as JSON-serialized values.
2018-10-17 18:22:10 +08:00
- **Observation:** Observe changes to keys.
- **Lightweight:** It's only ~300 lines of code.
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
2018-10-17 18:34:30 +08:00
#### SwiftPM
2018-04-12 01:19:30 +08:00
```swift
2019-07-25 09:54:14 +08:00
.package(url: "https://github.com/sindresorhus/Defaults", from: "2.0.2")
2018-04-12 01:19:30 +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
}
```
You can then access it as a subscript on the `defaults` global (note lowercase):
```swift
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:
```swift
extension Defaults.Keys {
2018-10-17 18:22:10 +08:00
static let name = OptionalKey< Double > ("name")
2018-04-12 01:19:30 +08:00
}
if let name = defaults[.name] {
print(name)
}
```
2019-08-15 18:48:10 +08:00
The default value is then `nil` .
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
}
defaults[.defaultDuration].rawValue
//=> "1 Hour"
```
### It's just UserDefaults with sugar
This works too:
```swift
extension Defaults.Keys {
2018-10-17 18:22:10 +08:00
static let isUnicorn = Key< Bool > ("isUnicorn", default: true)
2018-04-12 01:19:30 +08:00
}
UserDefaults.standard[.isUnicorn]
//=> true
```
### Shared UserDefaults
```swift
2018-10-17 18:22:10 +08:00
let extensionDefaults = UserDefaults(suiteName: "com.unicorn.app")!
2018-04-12 01:19:30 +08:00
extension Defaults.Keys {
2018-10-17 18:22:10 +08:00
static let isUnicorn = Key< Bool > ("isUnicorn", default: true, suite: extensionDefaults)
2018-04-12 01:19:30 +08:00
}
2018-10-17 18:22:10 +08:00
defaults[.isUnicorn]
//=> true
// Or
2018-04-12 01:19:30 +08:00
extensionDefaults[.isUnicorn]
//=> true
```
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)
defaults[isUnicorn]
//=> true
```
### Observe changes to a key
```swift
extension Defaults.Keys {
static let isUnicornMode = Key< Bool > ("isUnicornMode", default: false)
}
let observer = defaults.observe(.isUnicornMode) { 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
```
2019-05-09 19:08:18 +08:00
In contrast to the native `UserDefaults` key observation, here you receive a strongly-typed change object.
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)
}
defaults[.isUnicornMode] = true
//=> true
defaults.reset(.isUnicornMode)
defaults[.isUnicornMode]
//=> false
```
This works for `OptionalKey` too, which will be reset back to `nil` .
2018-10-17 18:22:10 +08:00
### 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.
```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
### `let defaults = Defaults()`
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.
2018-10-17 18:22:10 +08:00
The default value is written to the actual `UserDefaults` and can be used elsewhere. For example, with Interface Builder binding.
#### `Defaults.OptionalKey` *(alias `Defaults.Keys.OptionalKey`)*
```swift
Defaults.OptionalKey< T > (_ key: String, suite: UserDefaults = .standard)
```
2018-04-12 01:19:30 +08:00
Type: `class`
Create a key with an optional value.
2018-10-17 18:22:10 +08:00
#### `Defaults#clear`
```swift
clear(suite: UserDefaults = .standard)
```
2018-04-12 01:19:30 +08:00
Type: `func`
Clear the user defaults.
2018-10-17 18:22:10 +08:00
#### `Defaults#observe`
```swift
observe< T: Codable > (
_ key: Defaults.Key< T > ,
options: NSKeyValueObservingOptions = [.initial, .old, .new],
handler: @escaping (KeyChange< T > ) -> Void
) -> DefaultsObservation
```
```swift
observe< T: Codable > (
_ key: Defaults.OptionalKey< T > ,
options: NSKeyValueObservingOptions = [.initial, .old, .new],
handler: @escaping (OptionalKeyChange< T > ) -> Void
) -> DefaultsObservation
```
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.
2018-04-12 01:19:30 +08:00
## FAQ
### 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
## Related
2018-06-29 16:49:06 +08:00
- [Preferences ](https://github.com/sindresorhus/Preferences ) - Add a preferences window to your macOS app in minutes
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 )