-2

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 = [""]
    }

}
Sureshtrb
  • 51
  • 11
  • 1
    This isn't directly relevant to your question, but using the variable name `userDefaults` to contain a value you _read_ from UserDefaults is truly awful. – Duncan C Sep 11 '18 at 13:42
  • You are trying to compare an optional string array with a string. – ADG Sep 11 '18 at 17:38

2 Answers2

2

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] ?? []
}
vadian
  • 274,689
  • 30
  • 353
  • 361
1

In your code userDefaults is of type [String]? and not String to be be campared to "". Binary operator == can only be used between two instances of the same type (This type has to adopt the Equatable protocol to use ==).

You may use this snippet to check that userDefaults is not nil :

if let defaults = userDefaults {
    persons = defaults
} else {
    persons = [""]
}

Or with the guard statement :

guard let defaults = userDefaults else {
    persons = [""]
    return
}
persons = defaults

Your final function would look like this:

func loadDefaults() {
    let userDefaults = UserDefaults.standard.object(forKey: "storedArray") as? [String]
    if let defaults = userDefaults {
        persons = defaults
    } else {
        persons = [""]
    }
}

Or :

func loadDefaults() {
    let userDefaults = UserDefaults.standard.object(forKey: "storedArray") as? [String]
    guard let defaults = userDefaults else {
        persons = [""]
        return
    }
    persons = defaults
}

P.S: persons = [""] means that the persons would contain one element, that is "". If you want an empty array use this: persons = []

ielyamani
  • 17,807
  • 10
  • 55
  • 90