Sorry, I didn't see this thread before I chimed in on Last expression as return value, and then again. As with the "then
pitch", you're on the right track, but as with guard
statements there, you're considering problems that actually don't have the possibility of being problems.
- Numbers are not valid labels.
- There is no ambiguity because the
break
has to return the value of the expression, and expressions can't exit outer scope*. This is true even in the probably-never-necessary situation of assigning to aVoid
variable.
label: do {
let voidValue = if condition {
let label = ()
break label // Would return `()` either way, but has to mean the variable because it's all that's available to an expression.
} else {
()
}
}
* From today's Swift:
let value: Void = {
label: do {
if true { break label } else { } // Compiles
return if true { () } else { () } // Compiles
return if true {
break label // Cannot 'break' in 'if' when used as expression
} else {
return // Cannot 'return' in 'if' when used as expression
}
}
} ()
As a precedent, there's no problem in current Swift with returning variables with the same names as labels.
The following compiles, but if you try putting
break label
before the return
in the if
or else
statement, you'll get
Missing return in closure expected to return 'Int'
.
let value = {
label: do {
if condition {
let label = 3
return label
} else {
return 4
}
}
} ()