Whenever it's been a little while since I used a switch case to bind an optional, I always, without fail, get it wrong the first time. e.g. the correct syntax is:
switch someOptional {
case let value?:
…
default:
…
}
…but I always instead intuitively reach for:
switch someOptional {
case let value:
…
default:
…
}
Not only does this not work as intended - that case will match any and all values, including nil
- but the compiler doesn't offer so much as a warning about it (maybe it'll issue a warning about what it thinks are redundant other cases, if they happen to be completely overshadowed).
(I think it should warn about this because, at least in simple cases like the above example, there's absolutely no point to the switch statement since only one case is ever reachable)
To me the 'correct' syntax is exactly opposite of what I expect. Appending a question mark suggests to me that the value can be optional.
This 'correct' syntax is also the opposite of that used in e.g. guard statements, where the question mark is not included:
guard let value = someOptional else { … }
Adding a question mark there is a compiler error.
And in fact you can use case
syntax in a guard statement to similarly get very unintuitive results:
guard case let someOptional else {
…
}
The above guard statement will never function, and the compiler doesn't even issue a warning about it.
(again, this feels like it should be a compiler warning at least - the compiler knows the guard statement has no function)
"In English", as it were, inserting "case" doesn't in any way change the apparent meaning of the statement - an unfamiliar reader could easily just assume that it's the "full" version of the syntax, and Swift merely allows the redundant case
keyword to be omitted for brevity.
I'm not necessarily critiquing the syntax as it is - rather, I'm hoping someone can rationalise this unintuitive & seemingly inconsistent syntax to me. I'm hoping that if I understand it better my brain will finally permanently remember the correct syntax.