Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay using DispatchTime.now() + float?

Tags:

swift

What exactly is going on with DispatchTime.now()

How come I can't assign the time to wait as a variable?

And How Could I use a variable ?

Given error >>>

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

var time : Float = 2.2 // <---time 

@IBAction func buttonPressed(_ sender: Any) {

    let when = DispatchTime.now() + 2.2 // <---- THIS IS OKAY
    DispatchQueue.main.asyncAfter(deadline: when){

        print("Hello")
    }

    let whenWhen = DispatchTime.now() + time // <---- THIS IS NOT OKAY
    DispatchQueue.main.asyncAfter(deadline: whenWhen){

        print("Hello")
    }
}
like image 978
Alex Avatar asked Dec 29 '17 10:12

Alex


3 Answers

DispatchTime.now() is a double. You cannot add a float and a double value together. (A small explanation about why can't you add values with different types can be found here).

Replace

var time: Float = 2.2

with

var time: Double = 2.2

And it will work fine.

like image 144
Dharmesh Kheni Avatar answered Nov 09 '22 20:11

Dharmesh Kheni


You can use DispatchTimeInterval to add time in DispatchTime.

For Example :

let whenWhen = DispatchTime.now() + DispatchTimeInterval.seconds(time)
DispatchQueue.main.asyncAfter(deadline: whenWhen){

    print("Hello")

}
like image 35
Jayesh Thanki Avatar answered Nov 09 '22 19:11

Jayesh Thanki


The error message pretty much explains it. You can't add a float and a DispatchTime together as they are different data types.

When you use this line:

let when = DispatchTime.now() + 2.2 // <---- THIS IS OKAY

you don't specify what type the 2.2 is and the system concludes it is of type DispatchTime and allows it.

However when you use this line:

let whenWhen = DispatchTime.now() + time // <---- THIS IS NOT OKAY

you have already determined that time is a float and that's where the error is generated.

It's probably easiest to convert like this:

DispatchTimeInterval.milliseconds(Int(time * 1000))
like image 6
Upholder Of Truth Avatar answered Nov 09 '22 21:11

Upholder Of Truth