It's not clear that we need to impose that limitation. There’s no precedent for that rule in other imperative languages that support conditional expressions. Swift's neighbors generally either (1) support function returns from condition expressions, (2) only have the ternary operator (or something isomorphic to the ternary), or (3) are functional languages that do not have return
statements at all.
Rust allows it:
fn foo(array: &[i32]) -> i32 {
let value = if array.is_empty() {
0
} else {
return 3 // ✅ returns from function
};
// do stuff with value
}
Ruby allows it:
def foo(array)
value = if array.empty?
0
else
return 3 # ✅ returns from function
end
# do stuff with value
end
Kotlin allows it:
fun foo(list: Collection<Int>): Int {
var value = if (list.isEmpty()) {
0
} else {
return 3 // ✅ returns from function
}
// do stuff with value
}
Scala allows it:
def foo(list: List[Int]): Int = {
var value = if (list.isEmpty) {
0
} else {
return 3 // ✅ returns from function
}
// do stuff with value
}
Javascript, C, C++, Dart, and PHP do not have conditional expressions (AFAICT); they only have the ternary operator.
Go does not even have the ternary operator! Assigning all branches to a local variable is the idiomatic approach.
Python at first seems to impose a limitation like Nate’s proposal. However, Python’s ___ if ___ else ___
expressions are really just its version of the ternary operator: its if
expressions have an entirely different syntax from if
statements, and do not support multiple statements. Python does not have the ?
:
spelling of the ternary operator. (Ceylon is similar.)
The closest thing I could find to a clear precedent for Nate’s proposed rule is Java’s switch expressions:
int value = switch (list.isEmpty()) {
case true -> 0;
case false -> return 3; // ❌ error: return outside of enclosing switch statement
};
I don't have a convenient C# dev environment handy. It would be interesting to check whether it supports int x = boolValue switch { true => 0, false => return 3 };
. It seems likely it follows Java’s precedent.