Search code examples
swiftarc4random

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

Solution

  • 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
    }