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
}
This is because you are setting the value of a optional String,
String?
KeychainWrapper.stringForKey("username")
to another optional StringretrievedString
.By trying to set a
String?
to anotherString?
, the if let check always succeeds, even when the value isnil
, 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-optionalString
tonil
, it will fail, because a non-optional cannot have a nil value. The code will then continue in theelse
statementYou should use