Search code examples
arraysswiftuserdefaults

Swift user defaults - array


Getting error on the below code as

Binary operator '==' cannot be applied to operands of type '[String]?' and 'String'

    func loadDefaults() {

    let userDefaults = UserDefaults.standard.object(forKey: "storedArray") as? [String]
    if (userDefaults == "") || userDefaults != nil{
        persons = userDefaults!
    }else{
        persons = [""]
    }

}

Solution

  • First of all there is a dedicated method array(forKey to retrieve an array.

    An empty array isEmpty, you cannot compare it with an empty String

    If you want to load the stored array or assign an empty array if the object can't be found use

    func loadDefaults() {
        // a variable name userDefaults for the array is confusing
        if let storedArray = UserDefaults.standard.array(forKey: "storedArray") as? [String] {
            persons = storedArray
        } else {
            persons = []
        }
    }
    

    or shorter

    func loadDefaults() {
        persons = UserDefaults.standard.array(forKey: "storedArray") as? [String] ?? []
    }