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

Viewed 4606

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
var dispatchAfter = DispatchTimeInterval.seconds(1)

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

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

Related