Checking if `if let` is nil

4.1k views Asked by At

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

There are 2 answers

2
Jojodmo On BEST ANSWER

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
}
0
Jeffery Thomas On

You are setting the type of retrievedString to be optional. The whole point of the check is to remove the optional and just have a String.

if let retrievedString: String = KeychainWrapper.stringForKey("username") {
    print("retrievedString: \(retrievedString)")
    //value not nil
} else {
    //Value is nil
}