I sometimes find when reading through more complex switch-case
statements, that as conditions accumulate, the statements can be more complicated to read than is necessary. While some of this comes down to encouraging good practices by developers, a syntactic sugar came to mind that might help in this effort.
That is, within switch
statements, allow consolidation of where
cases for a common let value
. It would do the following:
- Allow for grouping of related logic while reducing boilerplate
- Improve readability by enforcing use of an identical name for related logic on a common value.
func foo(parameter: Int) {
switch parameter {
case 1:
bar()
case 2..10:
baz()
case let value {
where condition:
value.function()...
where condition2:
value.function2()...
where (multipleCondition && multipleCondition2 && multipleCondition3) || multipleCondition4:
value.function2()...
where condition4:
value.function3()...
}
default:
break
}
}
It is functionally equivalent to the following constructions that I find deficient:
-
It is most similar to this construction. However this is more verbose than what I am proposing:
func foo(parameter: Int) { switch parameter { case 1: bar() case 2..10: baz() case let value switch value { case condition: value.function()... case condition2: value.function1()... case (multipleCondition && multipleCondition2 && multipleCondition3) || multipleCondition4: value.function2()... case condition4: value.function3()... } default: break } }
-
This construction is slightly more verbose (V1), but because there is no restriction on what name can be used the
case let
it allows each case to have a different name (V2), which can lead to a small cognitive penalty:
V1:
func foo(parameter: Int) {
switch parameter {
case 1:
bar()
case 2..10:
baz()
case let value where condition:
value.function()...
case let value where condition2:
value.function1()...
case let value where (multipleCondition && multipleCondition2 && multipleCondition3) || multipleCondition4:
value.function2()...
case let value where condition4:
value.function3()...
default:
break
}
}
V2:
func foo(parameter: Int) {
switch parameter {
case 1:
bar()
case 2..10:
baz()
case let value where condition:
value.function()...
case let valueDifferentName where condition2:
valueDifferentName.function()...
case let valueUniquelyName where (multipleCondition && multipleCondition2 && multipleCondition3) || multipleCondition4:
valueUniquelyName.function2()...
case let anotherValueName where condition4:
anotherValueName.function3()...
default:
break
}
}