Defaults.swift 2.1.0

Defaults.swift 2.1.0

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Nov 2016
SwiftSwift Version 3.0
SPMSupports SPM

Maintained by dalu93.



Defaults.swift

Easy to use UserDefaults for iOS apps.

BuddyBuild

Defaults.swift is a easy-to-use generic interface built on top of UserDefaults in Swift.

Features

  • [x] Compile time checks by using generics
  • [x] Swifty syntax
  • [x] Easy to use
  • [x] Fully extendable

Requirements

  • iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 8.0+
  • Swift 3.0+

Usage

Defaults.swift provides the user two different interfaces.

Define the keys

Defaults.swift uses a structure called DefaultKey<T> to handle the UserDefaults keys.

let defaultKey = DefaultKey<String>("key")

Retrieving a stored value

// Get the string value for the key. The method returns an Optional
let storedString = UserDefaults.standard.get(for: defaultKey)

Storing a new value

// Store a new value
UserDefaults.standard.set("hello", for: defaultKey)

Here is the power of Defaults.swift: you can’t store different types for the same key

UserDefaults.standard.set(10, for: defaultKey)  // this won't compile

Removing a value

// Delete the value from the storage
UserDefaults.standard.set(nil, for: defaultKey)

// or by calling
UserDefaults.standard.removeValue(for: defaultKey)

Migration

Migration from 1.x to 2.0.0

Compile fixes

The DefaultKey structure is now generic. Before you declared

let key = DefaultKey.Name(rawValue: "YOUR_KEY")!

Now, for a more type safety, you have to declare the type the key should hold. The internal struct Name doesn’t exist anymore

let key = DefaultKey<String>("YOUR_KEY")

Convenience methods

If you want to display, somehow, the key name in your code, you can replace

let key = yourDefaultKeyName.rawValue

to:

let key = yourDefaultKey.name

You can still compare two differents key by using the == operator. Pay attention that the application won’t compile if you’re going to compare two DefaultKey with different generic type. For example

let key = DefaultKey<String>("key")
let aKey = DefaultKey<Int>("key")
let otherKey = DefaultKey<String>("a")
let anotherKey = key

key == aKey         // this won't compile because they hold different types
key == otherKey     // this will return false because the name is different
key == anotherKey   // this will return true

License

Defaults.swift is released under the MIT license. See LICENSE for details.