Martin Algesten Martin Algesten - 4 months ago 416
Swift Question

How do I use Swift 3 scheduleRepeating?

It has something to do with

DispatchSourceTimer
, but I can't get anywhere.

This gives me an error about "ambiguous reference":

DispatchSourceTimer.scheduleRepeating(deadline:.now(), interval:.milliseconds(delay), leeway:.milliseconds(1))


My solution



The problem was to do with type confusion. Thanks matt for pointing me in the right direction. Here is my full result.

private var queueNo = 0
@discardableResult func repeater(_ delay:Int, _ closure:(()->())) -> (()->()) {
let queue = DispatchQueue(label: "repeater\(queueNo)", attributes: [])
queueNo += 1
let timer = DispatchSource.timer(flags: [], queue: queue)
let start = DispatchTime.now() + DispatchTimeInterval.milliseconds(delay)
timer.scheduleRepeating(deadline: start, interval: .milliseconds(delay), leeway: .milliseconds(1))
timer.setEventHandler {
DispatchQueue.main.async(execute: closure)
}
timer.resume()
return {
timer.cancel()
}
}

Answer

Change it to this:

DispatchSourceTimer.scheduleRepeating(deadline:.now(), interval:delay, leeway:.milliseconds(1))

Make sure delay is a Double. If you were expecting it to be milliseconds, you might have to divide first, because we want seconds here.