Search code examples
iosswiftxcodewhile-loopswift-playground

While loop with double conditional and || logical operator in Swift


I have a While Loop with a condition that limits it to repeat only 10 times, every time a cycle is repeated a constant D generates a random number in a range from 0 to 24, if D is 0, I change a variable dIsZero to true and prints the cycle where D is 0 for the first time.

var S = 0  
var dIsZero = false

while S < 10 || dIsZero == false {
    S += 1
    let D = Int.random(in: 0...24)
    if dIsZero == false && D == 0 {
        dIsZero = true
        print("D = 0 in a cycle \(S)/10")
    }
}

My problem is that I want the While Loop can also end when D is 0 before the 10 cycles are completed. I already tried to put the logical operator || but it doesn't work and I get the following results:

  • 10 cycles are exceeded until D is 0. For example: 84 cycles.

  • If D is 0 before 10 cycles, the loop does not stop until that 10 cycles
    are reached.

I read about the logical operators and found the following:

The Swift logical operators && and || are left-associative, meaning that compound expressions with multiple logical operators evaluate the leftmost subexpression first.

What solution do you recommend?


Solution

  • You just need to break loop

    while S < 10  {
        S += 1
        let D = Int.random(in: 0...24)
         if D == 0 {
           print("D = 0 in a cycle \(S)/10")
            break
         }
    }