Check if `if let` is zero

I have an application in which I am currently using SwiftKeychainWrapper . Below is the code that checks if there is any retrievedString nil. However, I still get retrievedString: nilin the console.

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

In this example, what is the correct way to use if-let to expand my optional value?

if let retrievedString: String? = KeychainWrapper.stringForKey("username") {
    print("retrievedString: \(retrievedString)")
    //value not nil
} else {
    //Value is nil
}
+4
source share
2 answers

This is because you are setting the value of an optional string String? KeychainWrapper.stringForKey("username")for another optional string retrievedString.

String? String?, if , nil, , nil.

String? String. Swift String nil, , nil. else

//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
}
+8

retrievedString . , String.

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

Source: https://habr.com/ru/post/1629648/


All Articles