Swiftpack.co - Package - sunshinejr/SwiftyUserDefaults


Platforms CI Status CocoaPods compatible Carthage compatible SPM compatible Swift version Swift version Swift version Swift version

Modern Swift API for NSUserDefaults

SwiftyUserDefaults makes user defaults enjoyable to use by combining expressive Swifty API with the benefits of static typing. Define your keys in one place, use value types easily, and get extra safety and convenient compile-time checks for free.

Previous versions' documentation: Version 4.0.0, Version 3.0.1
Migration guides: from 4.x to 5.x, from 4.0.0-alpha.1 to 4.0.0-alpha.3, from 3.x to 4.x

Version 5.0.0

FeaturesUsageCodableNSCodingRawRepresentableExtending existing typesCustom types

Property wrappersKVOdynamicMemberLookupLaunch argumentsUtilsInstallation


There's only one step to start using SwiftyUserDefaults:

Define your keys!

extension DefaultsKeys {
    var username: DefaultsKey<String?> { return .init("username") }
    var launchCount: DefaultsKey<Int> { return .init("launchCount", defaultValue: 0) }

And just use it ;-)

// Get and set user defaults easily
let username = Defaults[\.username]
Defaults[\.hotkeyEnabled] = true

// Modify value types in place
Defaults[\.launchCount] += 1
Defaults[\.volume] -= 0.1
Defaults[\.strings] += "โ€ฆ can easily be extended!"

// Use and modify typed arrays
Defaults[\.libraries][0] += " 2.0"

// Easily work with custom serialized types
Defaults[\.color] = NSColor.white
Defaults[\.color]?.whiteComponent // => 1.0

If you use Swift 5.1 - good news! You can also use keyPath dynamicMemberLookup:

Defaults.color = NSColor.white

See more at the KeyPath dynamicMemberLookup section.


Define your keys

To get the most out of SwiftyUserDefaults, define your user defaults keys ahead of time:

let colorKey = DefaultsKey<String>("color", defaultValue: "")

Just create a DefaultsKey object, put the type of the value you want to store in angle brackets, the key name in parentheses, and you're good to go. If you want to have a non-optional value, just provide a defaultValue in the key (look at the example above).

You can now use the Defaults shortcut to access those values:

Defaults[key: colorKey] = "red"
Defaults[key: colorKey] // => "red", typed as String

The compiler won't let you set a wrong value type, and fetching conveniently returns String.

Take shortcuts

For extra convenience, define your keys by extending magic DefaultsKeys class and adding static properties:

extension DefaultsKeys {
    var username: DefaultsKey<String?> { return .init("username") }
    var launchCount: DefaultsKey<Int> { return .init("launchCount", defaultValue: 0) }

And use the shortcut dot syntax:

Defaults[\.username] = "joe"
Defaults[\.launchCount] += 1

Supported types

SwiftyUserDefaults supports all of the standard NSUserDefaults types, like strings, numbers, booleans, arrays and dictionaries.

Here's a full table of built-in single value defaults:

| Single value | Array | | ---------------- | -------------------- | | String | [String] | | Int | [Int] | | Double | [Double] | | Bool | [Bool] | | Data | [Data] | | Date | [Date] | | URL | [URL] | | [String: Any] | [[String: Any]] |

But that's not all!


Since version 4, SwiftyUserDefaults support Codable! Just conform to DefaultsSerializable in your type:

final class FrogCodable: Codable, DefaultsSerializable {
    let name: String

No implementation needed! By doing this you will get an option to specify an optional DefaultsKey:

let frog = DefaultsKey<FrogCodable?>("frog")

Additionally, you've got an array support for free:

let froggies = DefaultsKey<[FrogCodable]?>("froggies")


NSCoding was supported before version 4, but in this version we take the support on another level. No need for custom subscripts anymore! Support your custom NSCoding type the same way as with Codable support:

final class FrogSerializable: NSObject, NSCoding, DefaultsSerializable { ... }

No implementation needed as well! By doing this you will get an option to specify an optional DefaultsKey:

let frog = DefaultsKey<FrogSerializable?>("frog")

Additionally, you've got an array support also for free:

let froggies = DefaultsKey<[FrogSerializable]?>("froggies")


And the last but not least, RawRepresentable support! Again, the same situation like with NSCoding and Codable:

enum BestFroggiesEnum: String, DefaultsSerializable {
    case Andy
    case Dandy

No implementation needed as well! By doing this you will get an option to specify an optional DefaultsKey:

let frog = DefaultsKey<BestFroggiesEnum?>("frog")

Additionally, you've got an array support also for free:

let froggies = DefaultsKey<[BestFroggiesEnum]?>("froggies")

Extending existing types

Let's say you want to extend a support UIColor or any other type that is NSCoding, Codable or RawRepresentable. Extending it to be SwiftyUserDefaults-friendly should be as easy as:

extension UIColor: DefaultsSerializable {}

If it's not, we have two options:
a) It's a custom type that we don't know how to serialize, in this case at Custom types
b) It's a bug and it should be supported, in this case please file an issue (+ you can use custom types method as a workaround in the meantime)

Custom types

If you want to add your own custom type that we don't support yet, we've got you covered. We use DefaultsBridges of many kinds to specify how you get/set values and arrays of values. When you look at DefaultsSerializable protocol, it expects two properties in each type: _defaults and _defaultsArray, where both are of type DefaultsBridge.

For instance, this is a bridge for single value data storing/retrieving using NSKeyedArchiver/NSKeyedUnarchiver:

public struct DefaultsKeyedArchiverBridge<T>: DefaultsBridge {

    public func get(key: String, userDefaults: UserDefaults) -> T? {
        return userDefaults.data(forKey: key).flatMap(NSKeyedUnarchiver.unarchiveObject) as? T

    public func save(key: String, value: T?, userDefaults: UserDefaults) {
        userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)

    public func deserialize(_ object: Any) -> T? {
        guard let data = object as? Data else { return nil }
        return NSKeyedUnarchiver.unarchiveObject(with: data) as? T

Bridge for default storing/retrieving array values:

public struct DefaultsArrayBridge<T: Collection>: DefaultsBridge {
    public func save(key: String, value: T?, userDefaults: UserDefaults) {
        userDefaults.set(value, forKey: key)

    public func get(key: String, userDefaults: UserDefaults) -> T? {
        return userDefaults.array(forKey: key) as? T

    public func deserialize(_ object: Any) -> T? {
        return nil

Now, to use these bridges in our type we simply declare it as follows:

struct FrogCustomSerializable: DefaultsSerializable {

    static var _defaults: DefaultsBridge<FrogCustomSerializable> { return DefaultsKeyedArchiverBridge() }
    static var _defaultsArray: DefaultsBridge<[FrogCustomSerializable]> { return DefaultsKeyedArchiverBridge() }

    let name: String

Unfortunately, if you find yourself in a situation where you need a custom bridge, you'll probably need to write your own:

final class DefaultsFrogBridge: DefaultsBridge {
    func get(key: String, userDefaults: UserDefaults) -> FrogCustomSerializable? {
        let name = userDefaults.string(forKey: key)
        return name.map(FrogCustomSerializable.init)

    func save(key: String, value: FrogCustomSerializable?, userDefaults: UserDefaults) {
        userDefaults.set(value?.name, forKey: key)

    func deserialize(_ object: Any) -> FrogCustomSerializable? {
        guard let name = object as? String else { return nil }

        return FrogCustomSerializable(name: name)

final class DefaultsFrogArrayBridge: DefaultsBridge {
    func get(key: String, userDefaults: UserDefaults) -> [FrogCustomSerializable]? {
        return userDefaults.array(forKey: key)?
            .compactMap { $0 as? String }

    func save(key: String, value: [FrogCustomSerializable]?, userDefaults: UserDefaults) {
        let values = value?.map { $0.name }
        userDefaults.set(values, forKey: key)

    func deserialize(_ object: Any) -> [FrogCustomSerializable]? {
        guard let names = object as? [String] else { return nil }

        return names.map(FrogCustomSerializable.init)

struct FrogCustomSerializable: DefaultsSerializable, Equatable {

    static var _defaults: DefaultsFrogBridge { return DefaultsFrogBridge() }
    static var _defaultsArray: DefaultsFrogArrayBridge { return DefaultsFrogArrayBridge() }

    let name: String

To support existing types with different bridges, you can extend it similarly:

extension Data: DefaultsSerializable {
    public static var _defaultsArray: DefaultsArrayBridge<[T]> { return DefaultsArrayBridge() }
    public static var _defaults: DefaultsDataBridge { return DefaultsDataBridge() }

Also, take a look at our source code (or tests) to see more examples of bridges. If you find yourself confused with all these bridges, please create an issue and we will figure something out.

Property wrappers

SwiftyUserDefaults provides property wrappers for Swift 5.1! The property wrapper, @SwiftyUserDefault, provides an option to use it with key path and options: caching or observing.

Caching means that we will store the value for you and do not hit the UserDefaults for value almost never, only for the first value fetch.

Observing means we will observe, via KVO, your property so you don't have to worry if it was saved somewhere else and you use caching.

Now usage! Given keys:

extension DefaultsKeys {
    var userColorScheme: DefaultsKey<String> { .init("userColorScheme", defaultValue: "default") }
    var userThemeName: DefaultsKey<String?> { .init("userThemeName") }
    var userLastLoginDate: DefaultsKey<Date?> { .init("userLastLoginDate") }

You can declare a Test struct:

struct Settings {
    @SwiftyUserDefault(keyPath: \.userColorScheme)
    var userColorScheme: String

    @SwiftyUserDefault(keyPath: \.userThemeName, options: .cached)
    var userThemeName: String?

    @SwiftyUserDefault(keyPath: \.userLastLoginDate, options: [.cached, .observed])
    var userLastLoginDate: Date?


KVO is supported for all the types that are DefaultsSerializable. However, if you have a custom type, it needs to have correctly defined bridges and serialization in them.

To observe a value:

let nameKey = DefaultsKey<String>("name", defaultValue: "")
Defaults.observe(key: nameKey) { update in
	// here you can access `oldValue`/`newValue` and few other properties

By default we are using [.old, .new] options for observing, but you can provide your own:

Defaults.observe(key: nameKey, options: [.initial, .old, .new]) { _ in }

KeyPath dynamicMemberLookup

SwiftyUserDefaults makes KeyPath dynamicMemberLookup usable in Swift 5.1!

extension DefaultsKeys {
    var username: DefaultsKey<String?> { return .init("username") }
    var launchCount: DefaultsKey<Int> { return .init("launchCount", defaultValue: 0) }

And just use it ;-)

// Get and set user defaults easily
let username = Defaults.username
Defaults.hotkeyEnabled = true

// Modify value types in place
Defaults.launchCount += 1
Defaults.volume -= 0.1
Defaults.strings += "โ€ฆ can easily be extended!"

// Use and modify typed arrays
Defaults.libraries[0] += " 2.0"

// Easily work with custom serialized types
Defaults.color = NSColor.white
Defaults.color?.whiteComponent // => 1.0

Launch arguments

Do you like to customize your app/script/tests by UserDefaults? Now it's fully supported on our side, statically typed of course.

Note: for now we support only Bool, Double, Int, String values, but if you have any other requests for that feature, please open an issue or PR and we can talk about implementing it in new versions.

You can pass your arguments in your schema:

Pass launch arguments in Xcode Schema editor.

Or you can use launch arguments in XCUIApplication:

func testExample() {
    let app = XCUIApplication()
    app.launchArguments = ["-skipLogin", "true", "-loginTries", "3", "-lastGameTime", "61.3", "-nickname", "sunshinejr"]

Or pass them as command line arguments!

./script -skipLogin true -loginTries 3 -lastGameTime 61.3 -nickname sunshinejr


Remove all keys

To reset user defaults, use removeAll method.


Shared user defaults

If you're sharing your user defaults between different apps or an app and its extensions, you can use SwiftyUserDefaults by overriding the Defaults shortcut with your own. Just add in your app:

var Defaults = DefaultsAdapter<DefaultsKeys>(defaults: UserDefaults(suiteName: "com.my.app")!, keyStore: .init())

Check key

If you want to check if we've got a value for DefaultsKey:

let hasKey = Defaults.hasKey(\.skipLogin)



Swift version >= 4.1
iOS version >= 8.0
macOS version >= 10.11
tvOS version >= 9.0
watchOS version >= 2.0


If you're using CocoaPods, just add this line to your Podfile:

pod 'SwiftyUserDefaults', '~> 5.0'

Install by running this command in your terminal:

pod install

Then import the library in all files where you use it:

import SwiftyUserDefaults


Just add to your Cartfile:

github "sunshinejr/SwiftyUserDefaults" ~> 5.0

Swift Package Manager

Just add to your Package.swift under dependencies:

let package = Package(
    name: "MyPackage",
    products: [...],
    dependencies: [
        .package(url: "https://github.com/sunshinejr/SwiftyUserDefaults.git", .upToNextMajor(from: "5.0.0"))
    targets: [...]

More like this

If you like SwiftyUserDefaults, check out SwiftyTimer, which applies the same swifty approach to NSTimer.

You might also be interested in my blog posts which explain the design process behind those libraries:


If you have comments, complaints or ideas for improvements, feel free to open an issue or a pull request.

Authors and license

Maintainer: ลukasz Mrรณz

Created by: Radek Pietruszewski

SwiftyUserDefaults is available under the MIT license. See the LICENSE file for more info.


Stars: 4062


Used By

Total: 0


5.0.0 - 2019-12-31 12:57:35

Finally version 5.0.0 is ready to go! After extensive testing we are releasing this version to the public. ๐Ÿš€

Very warm thank you to everyone participating in all these months of work: @marty-suzuki, @Z-JaDe, @philippec-ls and others that contributed to this project. On to the next year! ๐Ÿฅ‚

Note: There shouldn't be any differences between latest beta and this version so you should be ready to go with bumping the version in your favorite dependency manager. If you are migrating from version 4 and lower, please check our migration guides.

5.0.0-beta.5 - 2019-10-05 09:42:51

Unfortunately we had to remove Combine for now to keep Xcode 10 compatibility ๐Ÿ˜ญ You might want to update to that version ASAP as it's fixing crashes on release builds...


  • Removed Combine extensions for now. Due to problems with weak-linking the framework, it's too difficult to support it with ease using all package managers and also without breaking backwards-compatibility. Probably gonna introduce it once we only support Xcode 11. @sunshinejr

5.0.0-beta.4 - 2019-09-27 15:27:10

Fixed a pretty bad indexing/building issue... See Migration Guide for more.


  • Fixed an issue with Xcode freezing, never-finishing indexing/building the project when we used Defaults[\.keyPath] in conditional statement. Unfortunately we had to add key label to Defaults[key: DefaultsKey<String?>...] where you wouldn't have to add the label to the subscript before. @sunshinejr.

5.0.0-beta.3 - 2019-09-25 13:38:21

Fixes to package managers! ๐Ÿš€ Xcode 11 & Carthage are friends again. Also, you won't fetch testing libraries for SPM anymore so you can use your Xcode Previews again.


  • Fixed an issue with SPM integration - it no longer fetches testing libraries & doesn't create runtime crashes or Xcode Preview crashes anymore. @sunshinejr.
  • Fixed an issue where Carthage users using Xcode 11 couldn't install SwiftyUserDefaults 5. We added weak-linking for the xcodeproj so you might need additional steps for Xcode 10 + Carthage + SwiftyUserDefaults 5.* users. @sunshinejr.

5.0.0-beta.2 - 2019-09-09 18:09:18

This beta adds Combine support! Just use it on the DefaultsAdapter (if you can use Combine):

func obserColorScheme() {
    colorSchemeObserver = Defaults.publisher(for: \.colorSchemeObserver)
        .sink { value in

5.0.0-beta.1 - 2019-09-06 15:17:00

This cool release prepares for Swift 5.1 - we introduce key path access (enabling dynamicMemberLookup) and property wrapper! Additionally there are some changes to all Defaults global variable, DefaultsKeys and `DefaultsBridge - check out our migration guide for more.


  • Introduced DefaultsAdapter thats the main object for user defaults and the Defaults global variable. @marty-suzuki
  • Thanks to DefaultsAdapter, if you are using Swift 5.1 you can use dyanmic member lookup! This allows you to use Defaults.yourKey instead of Defaults[.yourKey]. In case you are not using Swift 5.1, you would need to transition to Defaults[\.yourKey] instead of Defaults[.yourKey]. @marty-suzuki
  • There is a new protocol, DefaultsKeyStore that DefaultsKeys conform to. This key store is then accepted by the DefaultsAdapter so you can have multiple key stores for multiple adapters! @marty-suzuki
  • Unfortunately the above means that you need to declare your keys as a computed properties instead of static stored ones.@marty-suzuki
  • DefaultsBridge is now a struct, not a class. You need to use composition instead of inheritance to compose them. @Z-JaDe
  • DefaultsBridge changed a little bit, there is no isSerialized property anymore, if you create your own bridge you need to provide deserialize() method as well. @Z-JaDe
  • Added @SwiftyUserDefault property wrapper for Swift 5.1 users! It uses key paths and has options to cache/observe your defaults as well. @sunshinejr
  • Updated project to recommended settings of Xcode 10.2. @philippec-ls

4.0.0 - 2019-04-26 15:52:34

4.0.0 is finally out. A lot of cool features and improvements for you to try today! ๐Ÿš€

Changes from 4.0.0-beta.2 to 4.0.0

  • Updated DefaultsKey.defaultValue access level to public. @DivineDominion
  • Updated access level of all bridges to open from public. @fredpi

Read migration guide from version 3.x to 4.x

4.0.0-beta.2 - 2019-03-09 17:00:26

Minor stability update for Carthage users. This should fix the linking problem we've had in beta.1. No other fixes/updates were introduced in here.

4.0.0-beta.1 - 2019-02-25 09:05:02

This update introduces few cool additions to the library! ๐ŸŽ‰


  • Added support for launch arguments/plist for Bool, Double, Int, String values. @sunshinejr
  • Added support for KVO! DivineDominion, toshi0383, @sunshinejr
  • Brought back dictionary support for [String: Any]/[String: String] and corresponding array version of it [[String: Any]]/[[String: String]]. @sunshinejr

If you have already created a custom bridge for you type, and you want to use it with KVO, you'll need to override two new functions: isSerialized() and deserialize(_:). See Readme for more instructions.

4.0.0-alpha.3 - 2019-02-19 16:02:43

This is a small update over 4.0.0-alpha.2 with two fixes.

Migration guide from 3.x to 4.x Migration guide from 4.0.0-alpha.1 to 4.0.0-alpha.2


4.0.0-alpha.2 - 2019-02-18 09:11:58


We're back with alpha 2!

Migration guide from 3.x to 4.x Migration guide from 4.0.0-alpha.1 to 4.0.0-alpha.2


  • Swift 4.2 support. @sunshinejr
  • Early Swift 5.0 support! @sunshinejr
  • Rewritten core. We use DefaultsBridges now to define getters/setters for given type. @sunshinejr
  • Fixed a bug where you couldn't extend non-final class like NSColor. @sunshinejr
  • Removed type-based default values. This means you need to use key-based defaultValue or use an optional DefaultsKey from now on. @sunshinejr
  • Improved CI infra: Swift 4.1/4.2/5.0 builds with CocoaPods/Carthage/SPM integration scripts. @sunshinejr

4.0.0-alpha.1 - 2018-05-08 20:07:36


This is a huge release. Please try it out and let me know how it feels as we still have time for improvements!

Migration guide from 3.x to 4.x


  • Swift 4.1 support @sunshinejr
  • Added Codable support! @sunshinejr
  • Added generic subscripts support (better DefaultsKey init diagnostics and accessing Defaults[.key]) @sunshinejr
  • Added default values protocols (DefaultsDefaultValueType, DefaultsDefaultArrayValueType) - this means that you can extend any type with default value so you can create non-optional DefaultsKey afterwards! @sunshinejr
  • Added default values in DefaultsKey, e.g. DefaultsKey<String>("test", defaultValue: "default value") @sunshinejr
  • Added better support for custom types: using DefaultsSerializable, when your type implements NSCoding, RawRepresentable (enums as well) or Codable, you get default implementations for free! @sunshinejr
  • Added automatic array support for any type that is available to SwiftyUserDefaults (means custom with DefaultsSerializable as well!) @sunshinejr
  • Added Swift Package Manager support! @sunshinejr
  • Added [URL] built-in support! @sunshinejr
  • A lot of infrastructure changes (CI, project), around 350 tests to make sure all of the changes work properly! @sunshinejr
  • Removed legacy strings based API (Defaults["test"]), Dictionary and Any support (sorry, with all the changes in the library we had to, but you probably can bring it back with DefaultsSerializable anyways ๐Ÿ˜…) @sunshinejr