{"id":1014,"url":"https://github.com/sindresorhus/Defaults","last_synced_at":"2025-08-06T13:32:05.518Z","repository":{"id":37920460,"uuid":"129132562","full_name":"sindresorhus/Defaults","owner":"sindresorhus","description":"💾 Swifty and modern UserDefaults","archived":false,"fork":false,"pushed_at":"2025-05-12T18:27:30.000Z","size":390,"stargazers_count":2309,"open_issues_count":29,"forks_count":143,"subscribers_count":15,"default_branch":"main","last_synced_at":"2025-07-30T20:37:51.217Z","etag":null,"topics":["ios","macos","nsuserdefaults","storage","swift-package","swift-package-manager","swiftui-components","swifty","userdefaults"],"latest_commit_sha":null,"homepage":"https://swiftpackageindex.com/sindresorhus/Defaults/documentation/defaults","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sindresorhus.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"license","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"sindresorhus","open_collective":"sindresorhus","buy_me_a_coffee":"sindresorhus","custom":"https://sindresorhus.com/donate"}},"created_at":"2018-04-11T17:49:02.000Z","updated_at":"2025-07-29T07:10:05.000Z","dependencies_parsed_at":"2023-10-13T11:08:28.111Z","dependency_job_id":"706329a2-bcc3-460a-9371-4187749c0684","html_url":"https://github.com/sindresorhus/Defaults","commit_stats":{"total_commits":147,"total_committers":15,"mean_commits":9.8,"dds":"0.23129251700680276","last_synced_commit":"4c009d5c2496e7aa126e922c94dd3d6ae049efa2"},"previous_names":[],"tags_count":42,"template":false,"template_full_name":null,"purl":"pkg:github/sindresorhus/Defaults","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sindresorhus%2FDefaults","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sindresorhus%2FDefaults/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sindresorhus%2FDefaults/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sindresorhus%2FDefaults/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sindresorhus","download_url":"https://codeload.github.com/sindresorhus/Defaults/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sindresorhus%2FDefaults/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":268660731,"owners_count":24286042,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-04T02:00:09.867Z","response_time":79,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ios","macos","nsuserdefaults","storage","swift-package","swift-package-manager","swiftui-components","swifty","userdefaults"],"created_at":"2024-01-05T20:15:37.064Z","updated_at":"2025-08-06T13:32:05.183Z","avatar_url":"https://github.com/sindresorhus.png","language":"Swift","readme":"# Defaults\n\n\u003e Swifty and modern [UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults)\n\nStore key-value pairs persistently across launches of your app.\n\nIt uses `UserDefaults` underneath but exposes a type-safe facade with lots of nice conveniences.\n\nIt's used in production by [all my apps](https://sindresorhus.com/apps) (4 million+ users).\n\n## Highlights\n\n- **Strongly typed:** You declare the type and default value upfront.\n- **SwiftUI:** Property wrapper that updates the view when the `UserDefaults` value changes.\n- **Codable support:** You can store any [Codable](https://developer.apple.com/documentation/swift/codable) value, like an enum.\n- **NSSecureCoding support:** You can store any [NSSecureCoding](https://developer.apple.com/documentation/foundation/nssecurecoding) value.\n- **Observation:** Observe changes to keys.\n- **Debuggable:** The data is stored as JSON-serialized values.\n- **Customizable:** You can serialize and deserialize your own type in your own way.\n- **iCloud support:** Automatically synchronize data between devices.\n\n## Benefits over `@AppStorage`\n\n- You define strongly-typed identifiers in a single place and can use them everywhere.\n- You also define the default values in a single place instead of having to remember what default value you used in other places.\n- You can use it outside of SwiftUI.\n- You can observe value updates.\n- Supports many more types, even `Codable`.\n- Easy to add support for your own custom types.\n- Comes with a convenience SwiftUI `Toggle` component.\n\n## Compatibility\n\n- macOS 11+\n- iOS 14+\n- tvOS 14+\n- watchOS 9+\n- visionOS 1+\n\n## Install\n\nAdd `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).\n\n## Support types\n\n- `Int(8/16/32/64)`\n- `UInt(8/16/32/64)`\n- `Double`\n- `CGFloat`\n- `Float`\n- `String`\n- `Bool`\n- `Date`\n- `Data`\n- `URL`\n- `UUID`\n- `Range`\n- `ClosedRange`\n- `Codable`\n- `NSSecureCoding`\n- `Color` [^1] (SwiftUI)\n- `Color.Resolved` [^1] (SwiftUI)\n- `NSColor`\n- `UIColor`\n- `NSFontDescriptor`\n- `UIFontDescriptor`\n\nDefaults also support the above types wrapped in `Array`, `Set`, `Dictionary`, `Range`, `ClosedRange`, and even wrapped in nested types. For example, `[[String: Set\u003c[String: Int]\u003e]]`.\n\nFor more types, see the [enum example](#enum-example), [`Codable` example](#codable-example), or [advanced Usage](#advanced-usage). For more examples, see [Tests/DefaultsTests](./Tests/DefaultsTests).\n\nYou can easily add support for any custom type.\n\nIf a type conforms to both `NSSecureCoding` and `Codable`, then `Codable` will be used for the serialization.\n\n[^1]: [You cannot use `Color.accentColor`.](https://github.com/sindresorhus/Defaults/issues/139)\n\n## Usage\n\n[API documentation.](https://swiftpackageindex.com/sindresorhus/Defaults/documentation/defaults)\n\nYou declare the defaults keys upfront with a type and default value.\n\n**The key name must be ASCII, not start with `@`, and cannot contain a dot (`.`).**\n\n```swift\nimport Defaults\n\nextension Defaults.Keys {\n\tstatic let quality = Key\u003cDouble\u003e(\"quality\", default: 0.8)\n\t//            ^            ^         ^                ^\n\t//           Key          Type   UserDefaults name   Default value\n}\n```\n\nYou can then access it as a subscript on the `Defaults` global:\n\n```swift\nDefaults[.quality]\n//=\u003e 0.8\n\nDefaults[.quality] = 0.5\n//=\u003e 0.5\n\nDefaults[.quality] += 0.1\n//=\u003e 0.6\n\nDefaults[.quality] = \"🦄\"\n//=\u003e [Cannot assign value of type 'String' to type 'Double']\n```\n\nYou can also declare optional keys for when you don't want to declare a default value upfront:\n\n```swift\nextension Defaults.Keys {\n\tstatic let name = Key\u003cDouble?\u003e(\"name\")\n}\n\nif let name = Defaults[.name] {\n\tprint(name)\n}\n```\n\nThe default value is then `nil`.\n\nYou can also specify a dynamic default value. This can be useful when the default value may change during the lifetime of the app:\n\n```swift\nextension Defaults.Keys {\n\tstatic let camera = Key\u003cAVCaptureDevice?\u003e(\"camera\") { .default(for: .video) }\n}\n```\n\n---\n\n### Enum example\n\n```swift\nenum DurationKeys: String, Defaults.Serializable {\n\tcase tenMinutes = \"10 Minutes\"\n\tcase halfHour = \"30 Minutes\"\n\tcase oneHour = \"1 Hour\"\n}\n\nextension Defaults.Keys {\n\tstatic let defaultDuration = Key\u003cDurationKeys\u003e(\"defaultDuration\", default: .oneHour)\n}\n\nDefaults[.defaultDuration].rawValue\n//=\u003e \"1 Hour\"\n```\n\n*(This works as long as the raw value of the enum is any of the supported types)*\n\n### Codable example\n\n```swift\nstruct User: Codable, Defaults.Serializable {\n\tlet name: String\n\tlet age: String\n}\n\nextension Defaults.Keys {\n\tstatic let user = Key\u003cUser\u003e(\"user\", default: .init(name: \"Hello\", age: \"24\"))\n}\n\nDefaults[.user].name\n//=\u003e \"Hello\"\n```\n\n### Use keys directly\n\nYou are not required to attach keys to `Defaults.Keys`.\n\n```swift\nlet isUnicorn = Defaults.Key\u003cBool\u003e(\"isUnicorn\", default: true)\n\nDefaults[isUnicorn]\n//=\u003e true\n```\n\n### SwiftUI support\n\n#### `@Default` in `View`\n\nYou 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`.\n\n```swift\nextension Defaults.Keys {\n\tstatic let hasUnicorn = Key\u003cBool\u003e(\"hasUnicorn\", default: false)\n}\n\nstruct ContentView: View {\n\t@Default(.hasUnicorn) var hasUnicorn\n\n\tvar body: some View {\n\t\tText(\"Has Unicorn: \\(hasUnicorn)\")\n\t\tToggle(\"Toggle\", isOn: $hasUnicorn)\n\t\tButton(\"Reset\") {\n\t\t\t_hasUnicorn.reset()\n\t\t}\n\t}\n}\n```\n\nNote that it's `@Default`, not `@Defaults`.\n\nYou cannot use `@Default` in an `ObservableObject`. It's meant to be used in a `View`.\n\n#### `@ObservableDefault` in `@Observable`\n\nWith the `@ObservableDefault` macro, you can use `Defaults` inside `@Observable` classes that use the [Observation](https://developer.apple.com/documentation/observation) framework. Doing so is as simple as importing `DefaultsMacros` and adding two lines to a property (note that adding `@ObservationIgnored` is needed to prevent clashes with `@Observable`):\n\n\u003e [!IMPORTANT] \n\u003e Build times will increase when using macros.\n\u003e \n\u003e Swift macros depend on the [`swift-syntax`](https://github.com/swiftlang/swift-syntax) package. This means that when you compile code that includes macros as dependencies, you also have to compile `swift-syntax`. It is widely known that doing so has serious impact in build time and, while it is an issue that is being tracked (see [`swift-syntax`#2421](https://github.com/swiftlang/swift-syntax/issues/2421)), there's currently no solution implemented.\n\n```swift\nimport Defaults\nimport DefaultsMacros\n\n@Observable\nfinal class UnicornManager {\n\t@ObservableDefault(.hasUnicorn)\n\t@ObservationIgnored\n\tvar hasUnicorn: Bool\n}\n```\n\n#### `Toggle`\n\nThere's also a `SwiftUI.Toggle` wrapper that makes it easier to create a toggle based on a `Defaults` key with a `Bool` value.\n\n```swift\nextension Defaults.Keys {\n\tstatic let showAllDayEvents = Key\u003cBool\u003e(\"showAllDayEvents\", default: false)\n}\n\nstruct ShowAllDayEventsSetting: View {\n\tvar body: some View {\n\t\tDefaults.Toggle(\"Show All-Day Events\", key: .showAllDayEvents)\n\t}\n}\n```\n\nYou can also listen to changes:\n\n```swift\nstruct ShowAllDayEventsSetting: View {\n\tvar body: some View {\n\t\tDefaults.Toggle(\"Show All-Day Events\", key: .showAllDayEvents)\n\t\t\t// Note that this has to be directly attached to `Defaults.Toggle`. It's not `View#onChange()`.\n\t\t\t.onChange {\n\t\t\t\tprint(\"Value\", $0)\n\t\t\t}\n\t}\n}\n```\n\n### Observe changes to a key\n\n```swift\nextension Defaults.Keys {\n\tstatic let isUnicornMode = Key\u003cBool\u003e(\"isUnicornMode\", default: false)\n}\n\n// …\n\nTask {\n\tfor await value in Defaults.updates(.isUnicornMode) {\n\t\tprint(\"Value:\", value)\n\t}\n}\n```\n\nIn contrast to the native `UserDefaults` key observation, here you receive a strongly-typed change object.\n\n### Reset keys to their default values\n\n```swift\nextension Defaults.Keys {\n\tstatic let isUnicornMode = Key\u003cBool\u003e(\"isUnicornMode\", default: false)\n}\n\nDefaults[.isUnicornMode] = true\n//=\u003e true\n\nDefaults.reset(.isUnicornMode)\n\nDefaults[.isUnicornMode]\n//=\u003e false\n```\n\nThis works for a `Key` with an optional too, which will be reset back to `nil`.\n\n### Control propagation of change events\n\nChanges made within the `Defaults.withoutPropagation` closure will not be propagated to observation callbacks (`Defaults.observe()` or `Defaults.publisher()`), and therefore could prevent infinite recursion.\n\n```swift\nlet observer = Defaults.observe(keys: .key1, .key2) {\n\t\t// …\n\n\t\tDefaults.withoutPropagation {\n\t\t\t// Update `.key1` without propagating the change to listeners.\n\t\t\tDefaults[.key1] = 11\n\t\t}\n\n\t\t// This will be propagated.\n\t\tDefaults[.someKey] = true\n\t}\n```\n\n### It's just `UserDefaults` with sugar\n\nThis works too:\n\n```swift\nextension Defaults.Keys {\n\tstatic let isUnicorn = Key\u003cBool\u003e(\"isUnicorn\", default: true)\n}\n\nUserDefaults.standard[.isUnicorn]\n//=\u003e true\n```\n\n### Shared `UserDefaults`\n\n```swift\nlet extensionDefaults = UserDefaults(suiteName: \"com.unicorn.app\")!\n\nextension Defaults.Keys {\n\tstatic let isUnicorn = Key\u003cBool\u003e(\"isUnicorn\", default: true, suite: extensionDefaults)\n}\n\nDefaults[.isUnicorn]\n//=\u003e true\n\n// Or\n\nextensionDefaults[.isUnicorn]\n//=\u003e true\n```\n\n### Default values are registered with `UserDefaults`\n\nWhen 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.\n\n```swift\nextension Defaults.Keys {\n\tstatic let isUnicornMode = Key\u003cBool\u003e(\"isUnicornMode\", default: true)\n}\n\nprint(UserDefaults.standard.bool(forKey: Defaults.Keys.isUnicornMode.name))\n//=\u003e true\n```\n\n\u003e **Note** \n\u003e A `Defaults.Key` with a dynamic default value will not register the default value in `UserDefaults`.\n\n## API\n\n### `Defaults`\n\n#### `Defaults.Keys`\n\nType: `class`\n\nStores the keys.\n\n#### `Defaults.Key` _(alias `Defaults.Keys.Key`)_\n\n```swift\nDefaults.Key\u003cT\u003e(_ name: String, default: T, suite: UserDefaults = .standard)\n```\n\nType: `class`\n\nCreate a key with a default value.\n\nThe default value is written to the actual `UserDefaults` and can be used elsewhere. For example, with a Interface Builder binding.\n\n#### `Defaults.Serializable`\n\n```swift\npublic protocol DefaultsSerializable {\n\ttypealias Value = Bridge.Value\n\ttypealias Serializable = Bridge.Serializable\n\tassociatedtype Bridge: Defaults.Bridge\n\n\tstatic var bridge: Bridge { get }\n}\n```\n\nType: `protocol`\n\nTypes that conform to this protocol can be used with `Defaults`.\n\nThe type should have a static variable `bridge` which should reference an instance of a type that conforms to `Defaults.Bridge`.\n\n#### `Defaults.Bridge`\n\n```swift\npublic protocol DefaultsBridge {\n\tassociatedtype Value\n\tassociatedtype Serializable\n\n\tfunc serialize(_ value: Value?) -\u003e Serializable?\n\tfunc deserialize(_ object: Serializable?) -\u003e Value?\n}\n```\n\nType: `protocol`\n\nA `Bridge` is responsible for serialization and deserialization.\n\nIt has two associated types `Value` and `Serializable`.\n\n- `Value`: The type you want to use.\n- `Serializable`: The type stored in `UserDefaults`.\n- `serialize`: Executed before storing to the `UserDefaults` .\n- `deserialize`: Executed after retrieving its value from the `UserDefaults`.\n\n#### `Defaults.AnySerializable`\n\n```swift\nDefaults.AnySerializable\u003cValue: Defaults.Serializable\u003e(_ value: Value)\n```\n\nType: `class`\n\nType-erased wrapper for `Defaults.Serializable` values.\n\n- `get\u003cValue: Defaults.Serializable\u003e() -\u003e Value?`: Retrieve the value which type is `Value` from UserDefaults.\n- `get\u003cValue: Defaults.Serializable\u003e(_: Value.Type) -\u003e Value?`: Specify the `Value` you want to retrieve. This can be useful in some ambiguous cases.\n- `set\u003cValue: Defaults.Serializable\u003e(_ newValue: Value)`: Set a new value for `Defaults.AnySerializable`.\n\n#### `Defaults.reset(keys…)`\n\nType: `func`\n\nReset the given keys back to their default values.\n\nYou 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.\n\n#### `Defaults.removeAll`\n\n```swift\nDefaults.removeAll(suite: UserDefaults = .standard)\n```\n\nType: `func`\n\nRemove all entries from the given `UserDefaults` suite.\n\n#### `Defaults.withoutPropagation(_ closure:)`\n\nExecute the closure without triggering change events.\n\nAny `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.\n\n### `@Default(_ key:)`\n\nGet/set a `Defaults` item and also have the SwiftUI view be updated when the value changes.\n\n### Advanced\n\n#### `Defaults.CollectionSerializable`\n\n```swift\npublic protocol DefaultsCollectionSerializable: Collection, Defaults.Serializable {\n\tinit(_ elements: [Element])\n}\n```\n\nType: `protocol`\n\nA `Collection` which can store into the native `UserDefaults`.\n\nIt should have an initializer `init(_ elements: [Element])` to let `Defaults` do the de-serialization.\n\n#### `Defaults.SetAlgebraSerializable`\n\n```swift\npublic protocol DefaultsSetAlgebraSerializable: SetAlgebra, Defaults.Serializable {\n\tfunc toArray() -\u003e [Element]\n}\n```\n\nType: `protocol`\n\nA `SetAlgebra` which can store into the native `UserDefaults`.\n\nIt should have a function `func toArray() -\u003e [Element]` to let `Defaults` do the serialization.\n\n## Advanced usage\n\n### Custom types\n\nAlthough `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`.\n\n1. Create your own custom type.\n\n```swift\nstruct User {\n\tlet name: String\n\tlet age: String\n}\n```\n\n2. Create a bridge that conforms to `Defaults.Bridge`, which is responsible for handling serialization and deserialization.\n\n```swift\nstruct UserBridge: Defaults.Bridge {\n\ttypealias Value = User\n\ttypealias Serializable = [String: String]\n\n\tpublic func serialize(_ value: Value?) -\u003e Serializable? {\n\t\tguard let value else {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn [\n\t\t\t\"name\": value.name,\n\t\t\t\"age\": value.age\n\t\t]\n\t}\n\n\tpublic func deserialize(_ object: Serializable?) -\u003e Value? {\n\t\tguard\n\t\t\tlet object,\n\t\t\tlet name = object[\"name\"],\n\t\t\tlet age = object[\"age\"]\n\t\telse {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn User(\n\t\t\tname: name,\n\t\t\tage: age\n\t\t)\n\t}\n}\n```\n\n3. Create an extension of `User` that conforms to `Defaults.Serializable`. Its static bridge should be the bridge we created above.\n\n```swift\nstruct User {\n\tlet name: String\n\tlet age: String\n}\n\nextension User: Defaults.Serializable {\n\tstatic let bridge = UserBridge()\n}\n```\n\n4. Create some keys and enjoy it.\n\n```swift\nextension Defaults.Keys {\n\tstatic let user = Defaults.Key\u003cUser\u003e(\"user\", default: User(name: \"Hello\", age: \"24\"))\n\tstatic let arrayUser = Defaults.Key\u003c[User]\u003e(\"arrayUser\", default: [User(name: \"Hello\", age: \"24\")])\n\tstatic let setUser = Defaults.Key\u003cSet\u003cUser\u003e\u003e(\"user\", default: Set([User(name: \"Hello\", age: \"24\")]))\n\tstatic let dictionaryUser = Defaults.Key\u003c[String: User]\u003e(\"dictionaryUser\", default: [\"user\": User(name: \"Hello\", age: \"24\")])\n}\n\nDefaults[.user].name //=\u003e \"Hello\"\nDefaults[.arrayUser][0].name //=\u003e \"Hello\"\nDefaults[.setUser].first?.name //=\u003e \"Hello\"\nDefaults[.dictionaryUser][\"user\"]?.name //=\u003e \"Hello\"\n```\n\n### Dynamic value\n\nThere 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.\n\n`Defaults.AnySerializable` is only available for values that conform to `Defaults.Serializable`.\n\nWarning: 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`.\n\n#### Primitive type\n\n`Defaults.AnySerializable` conforms to `ExpressibleByStringLiteral`, `ExpressibleByIntegerLiteral`, `ExpressibleByFloatLiteral`, `ExpressibleByBooleanLiteral`, `ExpressibleByNilLiteral`, `ExpressibleByArrayLiteral`, and `ExpressibleByDictionaryLiteral`.\n\nWhich means you can assign these primitive types directly:\n\n```swift\nlet any = Defaults.Key\u003cDefaults.AnySerializable\u003e(\"anyKey\", default: 1)\nDefaults[any] = \"🦄\"\n```\n\n#### Other types\n\n##### Using `get` and `set`\n\nFor other types, you will have to assign it like this:\n\n```swift\nenum mime: String, Defaults.Serializable {\n\tcase JSON = \"application/json\"\n\tcase STREAM = \"application/octet-stream\"\n}\n\nlet any = Defaults.Key\u003cDefaults.AnySerializable\u003e(\"anyKey\", default: [Defaults.AnySerializable(mime.JSON)])\n\nif let mimeType: mime = Defaults[any].get() {\n\tprint(mimeType.rawValue)\n\t//=\u003e \"application/json\"\n}\n\nDefaults[any].set(mime.STREAM)\n\nif let mimeType: mime = Defaults[any].get() {\n\tprint(mimeType.rawValue)\n\t//=\u003e \"application/octet-stream\"\n}\n```\n\n#### Wrapped in `Array`, `Set`, or `Dictionary`\n\n`Defaults.AnySerializable` also support the above types wrapped in `Array`, `Set`, `Dictionary`.\n\nHere is the example for `[String: Defaults.AnySerializable]`:\n\n```swift\nextension Defaults.Keys {\n\tstatic let magic = Key\u003c[String: Defaults.AnySerializable]\u003e(\"magic\", default: [:])\n}\n\nenum mime: String, Defaults.Serializable {\n\tcase JSON = \"application/json\"\n}\n\n// …\nDefaults[.magic][\"unicorn\"] = \"🦄\"\n\nif let value: String = Defaults[.magic][\"unicorn\"]?.get() {\n\tprint(value)\n\t//=\u003e \"🦄\"\n}\n\nDefaults[.magic][\"number\"] = 3\nDefaults[.magic][\"boolean\"] = true\nDefaults[.magic][\"enum\"] = Defaults.AnySerializable(mime.JSON)\n\nif let mimeType: mime = Defaults[.magic][\"enum\"]?.get() {\n\tprint(mimeType.rawValue)\n\t//=\u003e \"application/json\"\n}\n```\n\nFor more examples, see [Tests/DefaultsAnySerializableTests](./Tests/DefaultsTests/DefaultsAnySeriliazableTests.swift).\n\n### Serialization for ambiguous `Codable` type\n\nYou may have a type that conforms to `Codable \u0026 NSSecureCoding` or a `Codable \u0026 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:\n\n```swift\nenum mime: String, Codable, Defaults.Serializable, Defaults.PreferRawRepresentable {\n\tcase JSON = \"application/json\"\n}\n\nextension Defaults.Keys {\n\tstatic let magic = Key\u003c[String: Defaults.AnySerializable]\u003e(\"magic\", default: [:])\n}\n\nprint(UserDefaults.standard.string(forKey: \"magic\"))\n//=\u003e application/json\n```\n\nHad we not added `Defaults.PreferRawRepresentable`, the stored representation would have been `\"application/json\"` instead of `application/json`.\n\nThis 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.\n\n### Custom `Collection` type\n\n1. Create your `Collection` and make its elements conform to `Defaults.Serializable`.\n\n```swift\nstruct Bag\u003cElement: Defaults.Serializable\u003e: Collection {\n\tvar items: [Element]\n\n\tvar startIndex: Int { items.startIndex }\n\tvar endIndex: Int { items.endIndex }\n\n\tmutating func insert(element: Element, at: Int) {\n\t\titems.insert(element, at: at)\n\t}\n\n\tfunc index(after index: Int) -\u003e Int {\n\t\titems.index(after: index)\n\t}\n\n\tsubscript(position: Int) -\u003e Element {\n\t\titems[position]\n\t}\n}\n```\n\n2. Create an extension of `Bag` that conforms to `Defaults.CollectionSerializable`.\n\n```swift\nextension Bag: Defaults.CollectionSerializable {\n\tinit(_ elements: [Element]) {\n\t\tself.items = elements\n\t}\n}\n```\n\n3. Create some keys and enjoy it.\n\n```swift\nextension Defaults.Keys {\n\tstatic let stringBag = Key\u003cBag\u003cString\u003e\u003e(\"stringBag\", default: Bag([\"Hello\", \"World!\"]))\n}\n\nDefaults[.stringBag][0] //=\u003e \"Hello\"\nDefaults[.stringBag][1] //=\u003e \"World!\"\n```\n\n### Custom `SetAlgebra` type\n\n1. Create your `SetAlgebra` and make its elements conform to `Defaults.Serializable \u0026 Hashable`\n\n```swift\nstruct SetBag\u003cElement: Defaults.Serializable \u0026 Hashable\u003e: SetAlgebra {\n\tvar store = Set\u003cElement\u003e()\n\n\tinit() {}\n\n\tinit(_ store: Set\u003cElement\u003e) {\n\t\tself.store = store\n\t}\n\n\tfunc contains(_ member: Element) -\u003e Bool {\n\t\tstore.contains(member)\n\t}\n\n\tfunc union(_ other: SetBag) -\u003e SetBag {\n\t\tSetBag(store.union(other.store))\n\t}\n\n\tfunc intersection(_ other: SetBag) -\u003e SetBag {\n\t\tvar setBag = SetBag()\n\t\tsetBag.store = store.intersection(other.store)\n\t\treturn setBag\n\t}\n\n\tfunc symmetricDifference(_ other: SetBag) -\u003e SetBag {\n\t\tvar setBag = SetBag()\n\t\tsetBag.store = store.symmetricDifference(other.store)\n\t\treturn setBag\n\t}\n\n\t@discardableResult\n\tmutating func insert(_ newMember: Element) -\u003e (inserted: Bool, memberAfterInsert: Element) {\n\t\tstore.insert(newMember)\n\t}\n\n\tmutating func remove(_ member: Element) -\u003e Element? {\n\t\tstore.remove(member)\n\t}\n\n\tmutating func update(with newMember: Element) -\u003e Element? {\n\t\tstore.update(with: newMember)\n\t}\n\n\tmutating func formUnion(_ other: SetBag) {\n\t\tstore.formUnion(other.store)\n\t}\n\n\tmutating func formSymmetricDifference(_ other: SetBag) {\n\t\tstore.formSymmetricDifference(other.store)\n\t}\n\n\tmutating func formIntersection(_ other: SetBag) {\n\t\tstore.formIntersection(other.store)\n\t}\n}\n```\n\n2. Create an extension of `SetBag` that conforms to `Defaults.SetAlgebraSerializable`\n\n```swift\nextension SetBag: Defaults.SetAlgebraSerializable {\n\tfunc toArray() -\u003e [Element] {\n\t\tArray(store)\n\t}\n}\n```\n\n3. Create some keys and enjoy it.\n\n```swift\nextension Defaults.Keys {\n\tstatic let stringSet = Key\u003cSetBag\u003cString\u003e\u003e(\"stringSet\", default: SetBag([\"Hello\", \"World!\"]))\n}\n\nDefaults[.stringSet].contains(\"Hello\") //=\u003e true\nDefaults[.stringSet].contains(\"World!\") //=\u003e true\n```\n\n## FAQ\n\n### How can I store a dictionary of arbitrary values?\n\nAfter `Defaults` v5, you don't need to use `Codable` to store dictionary, `Defaults` supports storing dictionary natively.\nFor `Defaults` support types, see [Support types](#support-types).\n\n### How is this different from [`SwiftyUserDefaults`](https://github.com/radex/SwiftyUserDefaults)?\n\nIt'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.\n\n## Maintainers\n\n- [Sindre Sorhus](https://github.com/sindresorhus)\n- [@hank121314](https://github.com/hank121314)\n\n**Former**\n\n- [Kacper Rączy](https://github.com/fredyshox)\n\n## Related\n\n- [KeyboardShortcuts](https://github.com/sindresorhus/KeyboardShortcuts) - Add user-customizable global keyboard shortcuts to your macOS app\n- [LaunchAtLogin](https://github.com/sindresorhus/LaunchAtLogin) - Add \"Launch at Login\" functionality to your macOS app\n- [DockProgress](https://github.com/sindresorhus/DockProgress) - Show progress in your app's Dock icon\n- [Gifski](https://github.com/sindresorhus/Gifski) - Convert videos to high-quality GIFs on your Mac\n- [More…](https://github.com/search?q=user%3Asindresorhus+language%3Aswift+archived%3Afalse\u0026type=repositories)\n","funding_links":["https://github.com/sponsors/sindresorhus","https://opencollective.com/sindresorhus","https://buymeacoffee.com/sindresorhus","https://sindresorhus.com/donate"],"categories":["Database","Libs","Swift","Samples","HarmonyOS","🛠 Examples","Data Management [🔝](#readme)","userdefaults"],"sub_categories":["Getting Started","Data Management","Windows Manager","Linter","Libraries"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsindresorhus%2FDefaults","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsindresorhus%2FDefaults","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsindresorhus%2FDefaults/lists"}