DotUserDefaults
NSUserDefaults + Enums = 🙌
.UserDefaults has two main functions. It will let you access NSUserDefaults using string type Enums, so you don't have to type .rawValue every time you want to use Enums as the keys of your NSUserDefaults. Also, this extension adds methods that will let you easily store RawRepresentable Enums in the NSUserDefaults.
Usage
import DotUserDefaults
Enums as NSUserDefaults keys
Normally you would define constants to access your user default values or, if you like to live dangerously, type in the string directly. Now, you can safely access NSUserDefaults via Enums without having to use rawValue all the time.
enum MyDefaults: String {
case WelcomeText = "welcomeText"
}
func viewDidLoad() {
super.viewDidLoad()
welcomeLabel.text = NSUserDefaults.standardUserDefaults().stringForKey(MyDefaults.WelcomeText)
}
func updateWelcomeText(text: String) {
NSUserDefaults.standardUserDefaults().setObject(text, forKey: MyDefaults.WelcomeText)
}
Storing Enums in NSUserDefaults
Out of the box, you can only store Objects in NSUserDefaults unless you're brave enough to use NSData to do the convertion. This convenience extension allows you to "store" and access enums without the need of much convertion. It's limited only to RawRepresentable enums of the type String, Int, Float, Double.
enum MyDefaults: String {
case WelcomeText = "welcomeText"
}
enum WelcomeText: String {
case Hai = "👋"
case Cheers = "🍻"
case Cool = "👌"
}
func viewDidLoad() {
super.viewDidLoad()
welcomeText = NSUserDefaults.standardUserDefaults().stringForKey(MyDefaults.WelcomeText)
}
func updateWelcomeText(text: WelcomeText) {
NSUserDefaults.standardUserDefaults().setObject(text, forKey: MyDefaults.WelcomeText)
}
Instalation
Carthage
To integrate DotUserDefaults into your project using Carthage, add to your Cartfile:
github "gustavosaume/DotUserDefaults" ~> 0.1 Run carthage update to build the framework and drag the built DotUseDefaults.framework into your Xcode project. See more instructions on the Carthage page.
Cocoapods
DotUserDefaults is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "DotUserDefaults"
Author
Gustavo Saume, gustavosaume@gmail.com
License
DotUserDefaults is available under the MIT license. See the LICENSE file for more info.