import Foundation
print("Hello")
for i in 0...100 {
usleep(.random(in: 1000...10000))
print("Current progress is \(i)%", terminator: "\r")
}
print("Done")
But for some reason it just doesn't work as expected, it just prints last one, with 100%, omitting live progress.
That’s because the standard output is buffered; it’s only sent to the terminal when a \n is encountered. You need to manually flush it (with fflush(stdout)) after sending new data:
import Foundation
print("Hello")
for i in 0...100 {
usleep(.random(in: 1000...10000))
print("Current progress is \(i)%", terminator: "\r")
fflush(stdout)
}
print("\nDone")
I also added a line return before the “Done”, to prevent it from replacing part of the “Current progress” text.