Claire Cho
Claire Cho

Reputation: 87

How to add a variable's integer to another variable's integer

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

Upvotes: 3

Views: 285

Answers (2)

Dominik Bucher
Dominik Bucher

Reputation: 2169

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
}

Upvotes: 2

rmaddy
rmaddy

Reputation: 318874

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

var randomAmountOfTime = Int(arc4random_uniform(5))
let when = DispatchTime.now() + DispatchTimeInterval.seconds(randomAmountOfTime)

Upvotes: 0

Related Questions