Search code examples
iosswiftprimesfunc

How to keep a Swift loop running indefinitely (forever)?


I have written a function which currently displays all of the prime numbers under 1000.

I can keep making 1000 bigger to generate more numbers, but I do not know how to make it keep going on forever once run.

func generatePrimes() {
    let numbers = 2...1000
    for n in numbers {
        var prime = true

        for i in 2..<n { 
            if n % i == 0 {
                prime = false
                break
            }
        }

        if prime == true {
            print(n)
        }
    }
}

Solution

  • You could use a while loop with the argument being true. That way, the loop would never end.

    func generatePrimes() {
        var n = 2
        while true {
            var prime = true
    
            for i in 2..<n { 
                if n % i == 0 {
                    prime = false
                    break
                }
            }
    
            if prime == true {
                print(n)
            }
    
            n += 1
        }
    }
    

    Note that we use a variable (n) and increment (add 1 to it) on each iteration of the while loop.

    If you want it to end when it hits some n, you can have a conditional that checks against n and break's out of the loop:

    var n = 2
    while true {
        if n == 1000 {
            break
        }
        n += 1
    }
    

    The above code will stop execution when n hits 1000 and will not print anything for that case.