0

I am trying to make a program that pastes a sentence from a txt file every second. It works without the DispatchQueue.main.asyncAfter(deadline: ). With it, it prints nothing, and immediately ends with exit code 0. Here is the program:

import Cocoa

let file = "slowreadText.txt"
let waitTime: TimeInterval = 1

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

    let fileURL = dir.appendingPathComponent(file)

    do {
        let text = try String(contentsOf: fileURL, encoding: .utf8)
        let sentences = text.components(separatedBy: ".")

        for i in 0..<sentences.count {
            let sentence = sentences[i]
            DispatchQueue.main.asyncAfter(deadline: .now() + (waitTime * Double(i))) {
                print(sentence)
            }
        }

    }catch {
        print(error)
    }
}
Victor Apeland
  • 110
  • 1
  • 10

1 Answers1

2

You need to call RunLoop.main.run() at the end of your script to prevent it from terminating.

ladislas
  • 3,037
  • 19
  • 27