I wanted to add a delay to a swift 3 program and found good examples here at SO using DispatchQueue.main.asyncAfter(). I tested it in Playground and it it does add a delay. What baffles me though is that adding a delay of 61 (secs.) apparently spends 67 secs.
let date1: Date = Date.init()
func print_delay(s: String) -> Void {
print(s)
}
func delay(d: Double) -> Void {
DispatchQueue.main.asyncAfter(deadline: .now() + d) {
let date2: Date = Date.init()
let calendar: Calendar = Calendar.current
let components: DateComponents = calendar.dateComponents([.year, .month, .day, .hour, .second], from: date1, to: date2)
print_delay(s: "delta: \(components.second!)")
}
}
let delay_array = [1.0, 5.9, 10.2, 22.1, 31.5, 40.9, 51.8, 61.0]
for item in delay_array {
delay(d: item)
}
delta: 1
delta: 5
delta: 10
delta: 22
delta: 34
delta: 42
delta: 56
delta: 67
So I tested the same code in a command line program to see if it was more accurate but it also have the difference in the time. This is on macos sierra, latest xcode and on a macbook pro from 2012.