You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We know intuitively as programmers that this code will always result in a String (from a typechecking perspective, not a runtime perspective). But it's difficult to detect this while typechecking; this will produce an error like
Invalid return type
| while true {
^^^^^
Function 'foo' has return type String, but this is of type Unit
We can get around this by adding a "return" value at the end of the function (after the loop), but it seems silly since we know this is unreachable (since all branches within the infinite loop either continue or return). This however, falls apart if we aren't guaranteed to have an infinite loop:
func foo(): String {
var done = false
while !done {
if 1 < 3 {
continue
} else if 1 == 1 {
done = true
} else {
return "asdf"
}
}
"foo" // <- control flow _might_ reach here now
}
This proposal is to consider having a special case to handle this - if we're in a while loop and the condition is the literaltrue, then we can say with 100% certainty that the loop will terminate if all branches either continue or return (again, "terminate" from a purely typechecking perspective). This seems like such an edge case, and is probably very uncommon, but it's one of those things that just makes the compiler feel a lot smarter.
The text was updated successfully, but these errors were encountered:
Let's say we have this function
We know intuitively as programmers that this code will always result in a
String
(from a typechecking perspective, not a runtime perspective). But it's difficult to detect this while typechecking; this will produce an error likeWe can get around this by adding a "return" value at the end of the function (after the loop), but it seems silly since we know this is unreachable (since all branches within the infinite loop either
continue
orreturn
). This however, falls apart if we aren't guaranteed to have an infinite loop:This proposal is to consider having a special case to handle this - if we're in a
while
loop and the condition is the literaltrue
, then we can say with 100% certainty that the loop will terminate if all branches eithercontinue
orreturn
(again, "terminate" from a purely typechecking perspective). This seems like such an edge case, and is probably very uncommon, but it's one of those things that just makes the compiler feel a lot smarter.The text was updated successfully, but these errors were encountered: