Search code examples
iosswiftnsuserdefaultsuserdefaults

Register multiple value types in UserDefaults with Swift 3


I am converting an old Swift 2 project to Swift 3. In the previous version I registered default values for unset user defaults in the AppDelegate like this:

let defaults = NSUserDefaults.standardUserDefaults()
let defaultValues = [
    "stringKey" : "",
    "intKey" : 50
]
defaults.registerDefaults(defaultValues as! [String : AnyObject])

Xcode was helping to convert it, but the autoconvert in Xcode wasn't working for the following error:

Heterogenous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional

The auto correct finally did work, but by that time I had written most of this question so I will just add the answer below rather than deleting the question. (Also, the auto convert suggestions were more wordy than the answer I am providing below.)

Notes

  • Here is an answer for registering a single type in Swift 3.
  • I am talking about registering, not setting, multiple default values.

Solution

  • Here is the syntax for Swift 3. I am including it in its context in the AppDelegate.

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
        override init() {
            let defaults = UserDefaults.standard
            let defaultValues : [String : Any] = [
                "stringKey" : "",
                "intKey" : 50
            ]
            defaults.register(defaults: defaultValues)
            super.init()
        }
    
        // ...
    }
    

    Remember that this does not set the values, it only provides some initial defaults for when the user has not yet set them.