1
\$\begingroup\$

I created the following class to ease UserDefaults get/set within my Swift project.

class MyDefaults {
    enum Key: String, CaseIterable {
        case email // String
        case password // String
    }
    static private let defaults = UserDefaults.standard
    static func set(_ value: Any?, key: Key) { // to set value using enum key
        defaults.setValue(value, forKey: key.rawValue)
    }
    static func get(key: Key) -> Any? { // get value using enum key
        return defaults.value(forKey: key.rawValue)
    }
    static func hasValue(key: Key) -> Bool { // check value if exist or nil
        return defaults.value(forKey: key.rawValue) != nil
    }
    static func removeAll() { // remove all stored values
        for key in Key.allCases {
            defaults.removeObject(forKey: key.rawValue)
        }
    }
}

The aim is to use the class as follows:

let email = MyDefaults.get(key: .email)
MyDefaults.set(email, key: .email)

Note: I used static in class method in order to use it as type i.s.o. class instance.

I'm not sure about the static for the property 'defaults'. Xcode complaints if I omit it.

Is above code correct and/or is there something I missed?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ note - there is a similar project: github.com/sindresorhus/Defaults \$\endgroup\$ Commented Mar 15 at 16:59
  • 1
    \$\begingroup\$ Use Property Wrappers. Take a look here or there. Passwords and sensitive data should never be stored in user defaults. \$\endgroup\$ Commented Mar 16 at 0:44

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.