I am asking for user input (this works) and trying to output different results depending on if the input was nil
, an empty string, or a non-empty string using a switch
clause (doesn't work).
The first attempt got me an error because I'm trying to compare an optional string with a non-optional string:
import Foundation
print("Hi, please enter a text:")
let userInput = readLine(stripNewline: true)
switch userInput {
case nil, "": // Error: (!) Expression pattern of type ‘String’ cannot match values of type ‘String?’
print("You didn’t enter anything.")
default:
print("You entered: \(userInput)")
}
Fair enough, so I create a optional empty string to compare to:
import Foundation
print("Hi, please enter a text:")
let userInput = readLine(stripNewline: true)
let emptyString: String? = "" // The new optional String
switch userInput {
case nil, emptyString: // Error: (!) Expression pattern of type ‘String?’ cannot match values of type ‘String?’
print("You didn’t enter anything.")
default:
print("You entered: \(userInput)")
}
So that gives me an error saying I cannot compare a ‘String?’ to a ‘String?’.
Why is that? Are they somehow still not the same type?
PS. I have the feeling that I'm missing something fundamental here, such as what Troy pointed out about optionals not being "the same type as the corresponding non-otpional type but with the additional possibility of not having a value" (not an exact quote, see his UPDATE at the end of the question: What does an exclamation mark mean in the Swift language?). But I'm stuck connecting the final dots why this isn't ok.