I am implementing UserDefault
string value ! = nil or !=""
! = 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....
}
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
.
PS: Make sure the array has at least 6 items before you call insert
at 5.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.