Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if `if let` is nil

I have an app where I'm currently using the SwiftKeychainWrapper. Below is the code I have which checks if retrievedString is nil. However I'm still getting retrievedString: nil in the console.

Shouldn't the code in the if-let statement not run, or am I using/understanding if-let incorrectly?

With the given example, what's the correct way to use if-let to unwrap my optional value?

if let retrievedString: String? = KeychainWrapper.stringForKey("username") {
    print("retrievedString: \(retrievedString)")
    //value not nil
} else {
    //Value is nil
}
like image 925
C. Wagner Avatar asked Feb 20 '16 02:02

C. Wagner


People also ask

How do you know if Optional is nil?

You can use if statement and compare optional with nil to find out whether a optional contains a value or not. You can use the comparison operator "equal to" operator ( == ) or the "not equal to" operator ( !=

How do you check if something is nil Swift?

In Swift, if we define a variable to be an optional variable, in that case, this variable can have no value at all. If optional variable is assigned with nil , then this says that there is no value in this variable. To check if this variable is not nil, we can use Swift Inequality Operator != .

How do you check if an int variable is null or empty in Swift?

You can use if let. if let is a special structure in Swift that allows you to check if an Optional holds a value, and in case it does – do something with the unwrapped value. But for Strings you can also use . isEmpty() If you have initialized it to "" .

Can let be nil in Swift?

If a given tag in the JSON data is missing, you'd set that property to nil. You use a constant because the value is fixed once the response object is initialized. If it's nil, it will be nil forever. If it contains a value, it will always contain that value and it can't be changed.


1 Answers

This is because you are setting the value of a optional String, String? KeychainWrapper.stringForKey("username") to another optional String retrievedString.

By trying to set a String? to another String?, the if let check always succeeds, even when the value is nil, because both the types are the same, and both can accept a nil value.

Instead, you should attempt to set the optional string, String? to a non-optional string, String. When Swift tries to set a non-optional String to nil, it will fail, because a non-optional cannot have a nil value. The code will then continue in the else statement

You should use

//notice the removal of the question mark
//                            |
//                            v
if let retrievedString: String = KeychainWrapper.stringForKey("username") {
    print("retrievedString: \(retrievedString)")
    //value not nil
} else {
    //value is nil
}
like image 92
Jojodmo Avatar answered Oct 12 '22 23:10

Jojodmo