After reading in the last Natasha the Robot blog on Swift, I experimented on the use of if case to replace switch when testing a single case.
I'm not sure I fully understand the syntax and have several points to confirm.
I have an enum with associated values
enum TestEnum : someType {
case A(valueForA: Int)
case B(valueForB: Int)
}
var testEnum: TestEnum .= A(0)The call with a switch
switch testEnum {
case .A(let retrieveValue) : doA
default : break
}It tests that .A matches testEnum and load associated value in retrieveValue or does it declare a new .A() constant loaded with the testEnum ?
This can be replaced by if case
if case let .A(retrieveValue) = testEnum { doA) }question : in this case, it declares a new .A() constant ?
I can also put the let inside or outside the (), and that gives the same result :
switch testEnum {
case let .A(retrieveValue) : doA
default : break
}or
if case .A(let retrieveValue) = testEnum { doA) }But here the syntax seems weird, because looks like a == test, but in fact it's an allocation ?
1. You can put the "let" inside or outside the parentheses, because you have the same choice in the "switch" case syntax. In the rare case where the enum case's associated value is a tuple, and you want a mixture of "let" and "var" bindings for different elements of the tuple, then you must of course put the "let" or "var" inside the parentheses, separately for each tuple element.
2. I don't exactly know what you mean by "a new .A() constant", but I think the answer is no. The "let" causes a binding to be made between the variable name inside the parentheses and the associated value of the enum. There is a "new" Int value being bound, not a new ".A () constant". In your example, it means "if testEnum is case A, then define a variable retrieveValue that contains the associated value from testEnum".
3. In general, I'd avoid the second style of "switch" statement, where you use a "default" case. You're better off listing all of the cases explicitly, so that if you ever add a new case "C" you'll get a compiler error telling you that your switch is not exhaustive, forcing you to make sure you handle the new case correctly.
By analogy, this would also mean avoiding "if case let" for such enums: to avoid falling through if you ever add new cases, without your being forced to re-examine the correctness of the test.
In addition, you're absolutely right that the "if case let" syntax looks weird. It's hard to remember how to code, it's hard to read, and it's totally unclear how to write some of the more complicated "case" patterns that you'd otherwise be able to use in a genuine "switch" statement. For that reason, although it's a cool concept, I'd give it a very wide berth, until and unless there's a more streamlined syntax.