[swift-evolution] Switch statement tuple labels

Alexis abeingessner at apple.com
Tue Jan 3 10:08:33 CST 2017


If the input has labels, including them in the pattern has clear value: the compiler can check that the labels you expected are there, preventing value swapping bugs. Being able to omit the labels in the pattern is a reasonable convenience to avoid repeating yourself over and over. But being able to insert arbitrary labels that don’t match anything from the input is very weird, because it doesn’t really make anything more convenient or give the compiler fuel to catch mistakes. 

The proposal is essentially asking for slightly nicer syntax for comments in patterns. That is,


switch (1, 2) {
case (width: 0, height: 0): 
…
}


is entirely equivalent to:


switch (1, 2) {
case (/*width:*/ 0, /*height:*/ 0): 
…
}



That said, there’s a very clear inconsistency here between if-case-let and switch-case-let, which you would expect to be semantically equivalent:



let t1: (Int, Int) = (0, 0)

// This works
if case let (a: 0, b: y5) = t1 {
  print("hello")
}

// This doesn't
switch t1 {
case let (a: 0, b: y6): 
    print("hallo")
}


So unless someone has a compelling argument that if-case-let and switch-case-let should be different, one of these should probably be changed. Unless the behaviour of if-case-let is *clearly* a random compiler bug that no one is relying on, then source stability dictates that switch should become more permissive and allow these “comment" labels. I don’t have enough background in this feature’s design to say either way.


More information about the swift-evolution mailing list