How to create an infinite loop in Swift

3 Answers

0 votes
// Infinite while true Loop

import Foundation

var count = 0

while true { // infinite loop
    print("Iteration: \(count)")

    if count == 3 {
        print("Breaking out of loop...")
        break
    }

    count += 1
}

print("Loop finished.")


/*
run:

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Breaking out of loop...
Loop finished.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite repeat { } while true Loop

import Foundation

var count = 0

repeat { // infinite loop
    print("Step: \(count)")

    if count == 3 {
        print("Breaking out of loop...")
        break
    }

    count += 1
} while true // infinite loop

print("Done.")



/*
run:

Step: 0
Step: 1
Step: 2
Step: 3
Breaking out of loop...
Done.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite Loop Using DispatchSourceTimer

import Foundation

var count = 0

// The timer fires every second, and setEventHandler will run forever 
// until you explicitly cancel the timer.

let timer = DispatchSource.makeTimerSource()
timer.schedule(deadline: .now(), repeating: 1.0)

timer.setEventHandler { // infinite loop
    print("Tick: \(count)")

    if count == 3 {
        print("Breaking out of loop...")
        timer.cancel()
    }

    count += 1
}

timer.resume()

RunLoop.main.run()



/*
run:

Tick: 0
Tick: 1
Tick: 2
Tick: 3
Breaking out of loop...

*/

 



answered Apr 11 by avibootz
edited Apr 11 by avibootz
...