An easy way to maintain UserDefaults key

You can use #function literal to get the property name as UserDefault key. In the following example, #function will get replaced by accessToken. Be aware, changing the property names may break functionality for the existing users.

extension UserDefaults {
    var accessToken: String? {
        get {
            return string(forKey: #function)
        }
        set {
            set(newValue, forKey: #function)
            synchronize()
        }
    }
}

Share this

Join

Search articles

Search titles, tags and article content.

    You've successfully subscribed to Developer Insider
    Your account is ready. Welcome to Developer Insider
    Welcome back! You've successfully signed in
    Success! Your account is fully activated, you now have access to all content.