mango
1
The following code is in my Swift lesson:
var password = "1"
while true {
//Execute some code here
}
My question is about the second line of code. It doesn't provide a condition before the true value. Is that allowed? Isn't this invalid syntax since it has no condition to check for true value? Aren't I supposed to state what condition to check for??
tera
2
true is a boolean expression and while wants just that - boolean expression. You can of course do this:
while true == true {
and also
while true == (true == true) { ...
but that's just silly, "while true" is enough.
"while true { ... }" is an infinite loop that will loop "forever" unless you put some break / return / throw statement inside the loop.
while true {
if someCondition { break }
}
2 Likes
In this case, true is literally the "condition".
For what it's worth, I've been programming for over a decade and a half and still think while true looks nonsensical, despite its ubiquity. A repeat statement without the following while would be much easier to understand.
3 Likes
tera
4
Indeed, and I was not even sure if repeat statement without a while is valid Swift or not - checked just now. It is not... Perhaps it should be?
2 Likes
mango
5
Okay, got it, thank you! (The true being an expression part is a suprise! I'm learning.)
1 Like
tera
6
Found the idea of "repeat" without "while" was already suggested, discussed and rejected 6 years ago.
1 Like
tera
8
In other languages about a third is for "loop" another third for "while true" / while 1". "Loop" looks somewhat nicer but it doesn't look realistic to add it to Swift at this point.