15

I'm trying to set a variable time delay for a timer in Swift4, but when I put in the variable I get the error:

Binary operator '+' cannot be applied to operands of type 'DispatchTime' and 'Int32'

I used the code:

let when = (DispatchTime.now() + (5 * x))

The Variable "x" is an Int32

Please help if you know how to fix it.

2 Answers 2

55
var dispatchAfter = DispatchTimeInterval.seconds(1)

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + dispatchAfter, execute: {
    // Do your thing
})
5

You could do this:

let x: Int32 = 2
let when = (DispatchTime.now().uptimeNanoseconds + (5 * UInt64(x)))

The problem is that you can not sum different types. And DispatchTime is represented using 64 bits (unsigned) so you can cast it using UInt64(x).

To get the UInt64 from DispatchTime you can use uptimeNanoseconds or rawValue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.