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