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.
Read Statically-typed NSUserDefaults for more information about this project.
Features • Usage • Custom types • Traditional API • Installation • More info
-------There's only two steps to using SwiftyUserDefaults:
Step 1: Define your keys
extension DefaultsKeys {
static let username = DefaultsKey<String?>("username")
static let launchCount = DefaultsKey<Int>("launchCount")
}
Step 2: Just use it!
// Get and set user defaults easily
let username = Defaults[.username]
Defaults[.hotkeyEnabled] = true
// Modify value types in place
Defaults[.launchCount]++
Defaults[.volume] += 0.1
Defaults[.strings] += "… can easily be extended!"
// Use and modify typed arrays
Defaults[.libraries].append("SwiftyUserDefaults")
Defaults[.libraries][0] += " 2.0"
// Easily work with custom serialized types
Defaults[.color] = NSColor.whiteColor()
Defaults[.color]?.whiteComponent // => 1.0
The convenient dot syntax is only available if you define your keys by extending magic DefaultsKeys
class. You can also just pass the DefaultsKey
value in square brackets, or use a more traditional string-based API. How? Keep reading.
To get the most out of SwiftyUserDefaults, define your user defaults keys ahead of time:
let colorKey = DefaultsKey<String>("color")
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.
You can now use the Defaults
shortcut to access those values:
Defaults[colorKey] = "red"
Defaults[colorKey] // => "red", typed as String
The compiler won't let you set a wrong value type, and fetching conveniently returns String
.
For extra convenience, define your keys by extending magic DefaultsKeys
class and adding static properties:
extension DefaultsKeys {
static let username = DefaultsKey<String?>("username")
static let launchCount = DefaultsKey<Int>("launchCount")
}
And use the shortcut dot syntax:
Defaults[.username] = "joe"
Defaults[.launchCount]
You can easily modify value types (strings, numbers, array) in place, as if you were working with a plain old dictionary:
// Modify value types in place
Defaults[.launchCount]++
Defaults[.volume] += 0.1
Defaults[.strings] += "… can easily be extended!"
// Use and modify typed arrays
Defaults[.libraries].append("SwiftyUserDefaults")
Defaults[.libraries][0] += " 2.0"
// Easily work with custom serialized types
Defaults[.color] = NSColor.whiteColor()
Defaults[.color]?.whiteComponent // => 1.0
SwiftyUserDefaults supports all of the standard NSUserDefaults
types, like strings, numbers, booleans, arrays and dictionaries.
Here's a full table:
Optional variant | Non-optional variant | Default value |
---|---|---|
String? |
String |
"" |
Int? |
Int |
0 |
Double? |
Double |
0.0 |
Bool? |
Bool |
false |
NSData? |
NSData |
NSData() |
[AnyObject]? |
[AnyObject] |
[] |
[String: AnyObject]? |
[String: AnyObject] |
[:] |
NSDate? |
n/a | n/a |
NSURL? |
n/a | n/a |
AnyObject? |
n/a | n/a |
NSString? |
NSString |
"" |
NSArray? |
NSArray |
[] |
NSDictionary? |
NSDictionary |
[:] |
You can mark a type as optional to get nil
if the key doesn't exist. Otherwise, you'll get a default value that makes sense for a given type.
Additionally, typed arrays are available for these types:
Array type | Optional variant |
---|---|
[String] |
[String]? |
[Int] |
[Int]? |
[Double] |
[Double]? |
[Bool] |
[Bool]? |
[NSData] |
[NSData]? |
[NSDate] |
[NSDate]? |
You can easily store custom NSCoding
-compliant types by extending NSUserDefaults
with this stub subscript:
extension NSUserDefaults {
subscript(key: DefaultsKey<NSColor?>) -> NSColor? {
get { return unarchive(key) }
set { archive(key, newValue) }
}
}
Just copy&paste this and change NSColor
to your class name.
Here's a usage example:
extension DefaultsKeys {
static let color = DefaultsKey<NSColor?>("color")
}
Defaults[.color] // => nil
Defaults[.color] = NSColor.whiteColor()
Defaults[.color] // => w 1.0, a 1.0
Defaults[.color]?.whiteComponent // => 1.0
If you don't want to deal with nil
when fetching a user default value, you can remove ?
marks and supply the default value, like so:
extension NSUserDefaults {
subscript(key: DefaultsKey<NSColor>) -> NSColor {
get { return unarchive(key) ?? NSColor.clearColor() }
set { archive(key, newValue) }
}
}
In addition to NSCoding
, you can store enum
values the same way:
enum MyEnum: String {
case A, B, C
}
extension NSUserDefaults {
subscript(key: DefaultsKey<MyEnum?>) -> MyEnum? {
get { return unarchive(key) }
set { archive(key, newValue) }
}
}
The only requirement is that the enum has to be RawRepresentable
by a simple type like String
or Int
.
if !Defaults.hasKey(.hotkey) {
Defaults.remove(.hotkeyOptions)
}
You can use the hasKey
method to check for key's existence in the user defaults. remove()
is an alias for removeObjectForKey()
, that also works with DefaultsKeys
shortcuts.
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 = NSUserDefaults(suiteName: "com.my.app")!
There's also a more traditional string-based API available. This is considered legacy API, and it's recommended that you use statically defined keys instead.
Defaults["color"].string // returns String?
Defaults["launchCount"].int // returns Int?
Defaults["chimeVolume"].double // returns Double?
Defaults["loggingEnabled"].bool // returns Bool?
Defaults["lastPaths"].array // returns NSArray?
Defaults["credentials"].dictionary // returns NSDictionary?
Defaults["hotkey"].data // returns NSData?
Defaults["firstLaunchAt"].date // returns NSDate?
Defaults["anything"].object // returns NSObject?
Defaults["anything"].number // returns NSNumber?
When you don't want to deal with the nil
case, you can use these helpers that return a default value for non-existing defaults:
Defaults["color"].stringValue // defaults to ""
Defaults["launchCount"].intValue // defaults to 0
Defaults["chimeVolume"].doubleValue // defaults to 0.0
Defaults["loggingEnabled"].boolValue // defaults to false
Defaults["lastPaths"].arrayValue // defaults to []
Defaults["credentials"].dictionaryValue // defaults to [:]
Defaults["hotkey"].dataValue // defaults to NSData()
If you're using CocoaPods, just add this line to your Podfile:
pod 'SwiftyUserDefaults'
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 "radex/SwiftyUserDefaults"
Simply copy Sources/SwiftyUserDefaults.swift
to your Xcode project.
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. Or ping me on Twitter.
Radek Pietruszewski
SwiftyUserDefaults is available under the MIT license. See the LICENSE file for more info.