#33: UserDefaults Subscripts in Swift

UserDefaults already has good typed APIs such as string(forKey:), bool(forKey:) and integer(forKey:), so you usually do not need a subscript.

If you like the syntax, though, you can add one:

extension UserDefaults {
    subscript(key: String) -> Any? {
        get { object(forKey: key) }
        set { set(newValue, forKey: key) }
    }
}

UserDefaults.standard["launchCount"] = 3
let value = UserDefaults.standard["launchCount"]

This is compact, but it loses type information. For app code, typed wrappers or small dedicated accessors are often safer.


I'm also on Twitter and GitHub.

Subscribe via RSS.