User Defaults in Swift and iOS 8

I like to use a UserDefaultsManager class to handle all of the values I store in NSUserDefaults. Using computed properties in Swift makes it even easier to do. You can even make class level computed properties so that you don’t need to bother with a Singleton or creating an instance of your UserDefaultsManager.

// UserDefaultsManager class

import Foundation

private let myPropertyKey = "myProperty"

class UserDefaultsManager {

    // Properties Stored in User Defaults

    class var myProperty: String {
        get {
            return NSUserDefaults.standardUserDefaults().valueForKey(myPropertyKey) as String
        }
        set(newMyProperty) {
            NSUserDefaults.standardUserDefaults().setValue(newMyProperty, forKey: myPropertyKey)
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }

}


...


// In your code

UserDefaultsManager.myProperty = "My new property value"
println("myProperty: \(UserDefaultsManager.myProperty)") // prints "My new property value"
Written on August 25, 2014