I would like to repeat the result of a function if the result had the wrong value:

Hi everyone, problem:
I would like to repeat the result of a function if the result had the wrong value:

var count = 1
I extract a random number "n" from 0 to 4

if it comes out 0: count -= 1
if 1: count -= 5
if it comes out 2: count += 1
if it comes out 3: count += 5
default: count

however, if count drops below 0, cancel the operation and repeat the extraction of n

I tried this way, but the result count = -4 comes out, which would be the only result that should not go out:

var count = 1

repeat{
let n = Int(arc4random_uniform(5))

switch n {
case 0:
    count -= 1
    print(count)
case 1:
    count -= 5
    print(count)
case 2:
    count += 1
    print(count)
case 3:
    count += 5
    print(count)
default:
    print(count)
}
guard count >= 0 else {break}

}
while count < 0 && count > 6

thanks

Hi @Kna,

Welcome to the Swift forums! This type of question is best asked on StackOverflow or other places devoted to coding. The Swift forums are for discussions around Swift specific issues and development, rather than general coding questions.

Terms of Service

Privacy Policy

Cookie Policy