SwiftyUserDefaults is a set of extensions to make the NSUserDefaults
API cleaner, nicer, and at home with Swift's syntax.
Read Swifty APIs: NSUserDefaults for more information about this project.
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?
SwiftyUserDefaults always returns nil
for non-existing values, also for numbers and booleans.
Defaults["color"] = "red"
Defaults["launchCount"] = 0
SwiftyUserDefaults infers the right type when setting values.
Defaults["color"] // => nil
Defaults["color"] ?= "white" // => "white"
Defaults["color"] ?= "red" // => "white"
Works like ||=
in other languages — sets value only if the left-hand side value is nil
.
Defaults["launchCount"] += 1
Defaults["launchCount"]++
You can use the +=
and ++
operators to easily work on integer values in the user defaults. If the key didn't exist before operation, the operators assume it was 0
.
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()
.
The simplest way to install this library is to copy Src/SwiftyUserDefaults.swift
to your project. There's no step two!
Note: Using Xcode 6.3 beta? You'll find a Swift 1.2-compatible version on the swift-1.2
branch
You can also install this library using CocoaPods. Just add this line to your Podfile:
pod 'SwiftyUserDefaults'
Then import library module like so:
import SwiftyUserDefaults
Note that this requires CocoaPods 0.36 as well as iOS 8 or OS X 10.9+
If you have comments, complaints or ideas for improvements, feel free to open an issue or a pull request.
Radek Pietruszewski
SwiftyUserDefaults is available under the MIT license. See the LICENSE file for more info.