[swift-evolution] [Idea] Wrap switch cases in curly braces

Haravikk swift-evolution at haravikk.me
Thu Jul 7 16:05:06 CDT 2016


> On 7 Jul 2016, at 21:07, G B via swift-evolution <swift-evolution at swift.org> wrote:
> 
> It has always seemed odd to me that `case`s use a colon as a delimiter rather than curly braces like everything else.  Is there a reason for this other than the legacy of C-like languages?  
> 
> If I wanted to write a series of branching `if` \ `else` statements I would do it like so:
> 
> if x==0      { print(0) }
> else if x==1 { print (1) }
> else if x==2 { print(2) }
> else         { print("other”) }
> 
> I believe all flow control is wrapped in curly braces, except for `case`s inside a `switch`:
> 
> switch x {
> case 0: print(0)
> case 1: print(1)
> case 2: print(2)
> default: print("other")
> }
> 
> 
> I feel like this would be more consistent with the rest of the syntax:
> 
> switch x {
> case 0 { print(0) }
> case 1 { print(1) }
> case 2 { print(2) }
> default { print("other”) }
> }
> 
> The colon syntax evokes a label, but the modern, complex `case` statements in Swift don’t act much like labels.

While I could maybe see this being an option, we already kind of have it thanks to do{} blocks:

	switch x {
		case 0: do {
			print(0)
		}
		case 1: do {
			print(1)
		}
		case 2: do {
			print(2)
		}
		default: do {
			print("other")
		}
	}

Not quite as pretty, but perfectly functional right now, but will many people use it if given the chance? If you need scoping then you probably have conditionals anyway, or you can just do{} blocks for those cases only, I don't really see the need to require them on all of them.

Personally I don't see the need; the case labels themselves are highlighted pretty clearly thanks to being keywords, and act as both the opening for their block, and the close of any previous block, meanwhile the whole switch has enclosing braces already. There's also the issue of scope; you can fall through from a case, so technically speaking the only scope may be the switch itself, as you could fall through every single case and thus visit everything on the way down.

So yeah, I think the construct kind of already makes sense as it is, it's just a bit of weird one conceptually.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160707/3e8e0dd9/attachment.html>


More information about the swift-evolution mailing list