Reputation: 103
I am implementing UserDefault
string value ! = nil or !=""
but my validation not working. How do I solve this?
if((UserDefaults.standard.string(forKey: "name")) != nil || UserDefaults.standard.string(forKey: "name") != "") {
self.items.insert(UserDefaults.standard.string(forKey: "name") ?? "", at: 5) // Always reaching here....
}
Upvotes: 0
Views: 195
Reputation: 11242
Check if there is value for the key by optional unwrapping. Then check if it is not empty. Then insert it to the array.
if let value = UserDefaults.standard.string(forKey: "name"), !value.isEmpty {
items.insert(value, at: 5)
}
The reason the if
is executed every time in your case is because you are using an OR (||
) instead of AND (&&
). So, the second condition is true even when there is no value for the key in the UserDefaults
.
P.S: Make sure the array has at least 6 items before you call insert
at 5.
Upvotes: 2