How to validate UserDefault value will or empty using Swift - ios

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....
}

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.

Related

Get String value from an optional in Swift 4

I am new to Swift and am trying to compare my Error description name with different String constants to show the user different results, based on the error.
I am using:
let errorName = errors.first?["name"].debugDescription
The value of errorName comes as "Optional(AlreadyActiveUser)" and when i compare this to my constant string "AlreadyActiveUser", i get false.
I have tried many things, but i am not able to get the value of the string inside the optional.
Someone, please help.
You can use optional binding in this case...
guard let errorName = errors.first?["name"].debugDescription as? String {
print("value is not present...")
return
}
print(errorName)
//here you can compare errorName == "AlreadyActiveUser"
you can use this
if let errorName = errors.first?["name"] as? String {
print(errorName)
//here you can compare errorName == "AlreadyActiveUser"
}
else
{
print("value is not present...")
}
try let errorName = errors.first!["name"].debugDescription
Notes that I forced wrapping first with ! instead of ?.

How can I make sure my guard statement doesn't proceed with a nil value?

I've been trying to implement a guard statement and I think I have the implementation correct except my code runs past the guard statement even when I pass in nil values. I basically keep the fields empty and hit a register button to run this piece of code, but it assigns empty values to email and password, and the code runs right past the "else" block. Some help would be appreciated.
guard let email = emailField.text, let password = passwordField.text, let name = nameField.text else {
print ("FYF: Form is not valid")
return
}
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
print(error!)
return
}
I used a breakpoint at the guard statement and stepped over it. When I checked the variables inspector it says the email and password field are nil. I think I may have implemented something wrong. Thank you!
Your code is correct and probably never will enter the guard clause. Here you are setting values of variables base on, I think, UIText fields. This fields when empty are not null. It's important to understand that an empty string is not the same thing as a null value. An empty string, represented as "" is still a string. A null value is, like JavaScript coders like to talk: has an undefined type. Your guard clause will fail only when you try to set a non nil property to nil value.
To solve this, you just change your guard clause to something like:
guard emailField.text.isEmpty == false, passwordField.text.isEmpty == false
Or
guard !emailField.text.isEmpty, !passwordField.text.isEmpty
UITextfield returns empty string "" by default if no text is entered. So your guard statement will always be true.
Check if UITextfield isn't empty instead of nil e.g.
guard let email = (emailField.text?.isEmpty == false ? tfTest1.text : nil) else {
print ("FYF: Form is not valid")
return
}
Hope it helps!

Multiple value checking with swifts guard statement?

Most of my searching here on SO is proving futile. My guard statement works as far as checking each value and correcting it if one is nil. However if two of the values are nil, then I crash unexpectedly finding nil while unwrapping an optional. How does one go about checking that multiple values are not nil using swifts guard statement?
func protectInput() {
guard Double(myAmount.text!) != nil else {
myAmount.text = "0.00"
return
}
guard Double(myRate.text!) != nil else {
myRate.text = "0.00"
return
}
guard Double(myFee.text!) != nil else {
myFee.text = "0.00"
return
}
}
Maybe I am completely on the wrong track, any help with an example would be appreciated. I have read all I can take in. I do not need to compare two values or have some complex comparison.
Guard statements aren't the right thing to use here. If any of them fail, then you will return from the function and your later statements won't get executed. So if myAmount doesn't have a valid value in it, you'll never correct myRate and myFee.
if Double(myAmount.text ?? "") == nil {
myAmount.text = "0.00"
}
This pattern would suit you better:
the text value isn't force unwrapped any more, which will prevent one potential crash - ?? is the nil coalescing operator which will use either the text value or, in this case, an empty string
there is no return so the function will check all of the values.

replacing nil value with other customized value

I am using a keychain wrapper written in Swift.
When value is nil, this wrapper I'm using automatically saves data as "nil" instead of saving as an actual nil value.
For ex, ["last_name" : "nil"].
In one of my label in my iOS app, I'm returning last_name value.
It bothers me that a text in label is saying "nil" when there supposed to be nothing.
I remember in Swift that there is a syntax like A ?? B which puts B instead if A is not valid. But I cannot remember it right now.
In my app, I want to something like below:
if the value I'm looking for is nil, then input "" instead of "nil"
If keychain["last_name"] == nil ?? ""
I know this is a horrible explanation but this is all I could come up with.
?? is the nil coalescing operator. It is used for unwrapping optionals — a ?? b is shorthand for a != nil ? a! : b.
You probably want to use the ternary operator instead. You could even combine them like this:
let lastName = keychain["last_name"] == "nil" ? "" : (keychain["last_name"] ?? "")
That said, it might be easier to just filter out these responses immediately after getting the keychain instead of checking every time:
var keychain = ["first_name" : "aaron", "last_name" : "nil"]
keychain.forEach { if $0.1 == "nil" { keychain.removeValueForKey($0.0) } }
print(keychain) //["first_name": "aaron"]
The $0 is a shorthand argument name. Here's the long form version of the same code:
keychain.forEach { (key, value) -> () in
if value == "nil" {
keychain.removeValueForKey(key)
}
}

Filter an array based on empty value in Swift

I am trying to filter an array of dictionaries. The below code is the sample of the scenario i am looking for
let names = [
[ "firstName":"Chris","middleName":"Alex"],
["firstName":"Matt","middleName":""],
["firstName":"John","middleName":"Luke"],
["firstName":"Mary","middleName":"John"],
]
The final result should be an array for whom there is a middle name.
This did the trick
names.filter {
if let middleName = $0["middleName"] {
return !middleName.isEmpty
}
return false
}
You can also use the nil-coalescing operator to express this quite succinctly:
let noMiddleName = names.filter { !($0["middleName"] ?? "").isEmpty }
This replaces absent middle names with empty strings, so you can handle either using .isEmpty (and then negate if you want to fetch those with middle names).
You can also use optional chaining and the nil-coalescing operator to express it another way:
let noMiddleName = names.filter { !($0["middleName"]?.isEmpty ?? true) }
$0["middleName"]?.isEmpty will call isEmpty if the value isn’t nil, but returns an optional (because it might have been nil). You then use ?? to substitute true for nil.
Slightly shorter:
let result = names.filter { $0["middleName"]?.isEmpty == false }
This handles all three possible cases:
If the middle name exists and is not an empty string, then
$0["middleName"]?.isEmpty evaluates to false and the predicate
returns true.
If the middle name exists and is empty string, then
$0["middleName"]?.isEmpty evaluates to true and the predicate
returns false.
If the middle name does not exist, then
$0["middleName"]?.isEmpty evaluates to nil and the predicate
returns false (because nil != false).
This also works fine
names.filter {
if let middleName = $0["middleName"] {
return middleName != ""
}
return false
}

Resources