Arjun Yadav
Arjun Yadav

Reputation: 1429

How do I write GCD asyncAfter in Swift 4?

In earlier versions of Swift this code works perfectly.

DispatchQueue.main.asyncAfter(deadline: .now() + delay) { timer in
    self.setOriginalState()
    self.shakeAnimation()
}

But in Swift 4 the following error appears:

Ambiguous reference to member 'asyncAfter(deadline:qos:flags:execute:)'

How can one create a delay before running a sequence of code in Swift 4?

Upvotes: 0

Views: 1461

Answers (2)

Tom E
Tom E

Reputation: 1607

The compiler doesn’t seem to be able to infer the type of parameters in the asyncAfter call. So you might want to specify the type like this:

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay)

If you still get the same error make sure delay is of type DispatchTimeInterval. Here’s another example:

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(300)

This should eventually silence the compiler.

Upvotes: 1

Andrea
Andrea

Reputation: 26385

Trying in playground it doesn't give any issue, that is just "missing" is the "timer" reference.

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    print("Dispatching after")
}

DispatchQueue.main.asyncAfter(deadline: .now() + 3, qos: .userInteractive, flags: []) {
    print("Dispatching after")
}

They both seems to work, are you sure that the problem isn't somewhere else?

Upvotes: 4

Related Questions