3

I'm trying to add randomAmountOfTime to DispatchTime.now() but it gives me an error.

Error:

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

Here's what I did:

var randomAmountOfTime = Int(arc4random_uniform(5))
let when = DispatchTime.now() + randomAmountOfTime
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Claire Cho
  • 87
  • 1
  • 11

2 Answers2

2

Dispatch Time is Floating point number, therefore you must pass Double type or DispatchTime as provided by @rmaddy. Swift cannot add together Int and DispatchTime (because there is no operator provided in DispatchTime, you could create your custom extension). The same goes for Float and DispatchTime - the methods for some reason aren't available in the private API.

This should do:

var randomAmountOfTime = Double(arc4random_uniform(5))

let when = DispatchTime.now() + randomAmountOfTime

for further understanding you can go here

Edit:

You could create your custom file (like DispatchTime+Int.swift) and create custom operator for Adding together Int and DispatchTime:

  public func + (left: Int, right: DispatchTime) -> DispatchTime {
    return Double(left) + right
}
Dominik Bucher
  • 2,120
  • 2
  • 16
  • 25
  • 1
    In this case it would be simpler to cast `arc4random_uniform(5)` to `Double` instead of `Int` then you can add it directly. – rmaddy Feb 04 '18 at 00:18
0

Assuming your randomAmountOfTime is seconds, you can use DispatchTimeInterval.seconds.

var randomAmountOfTime = Int(arc4random_uniform(5))
let when = DispatchTime.now() + DispatchTimeInterval.seconds(randomAmountOfTime)
rmaddy
  • 314,917
  • 42
  • 532
  • 579