0

First I created a randomDelay value using arc4random

Then I would like to add the randomDelay value to the DispatchQueue to create a random Time Delay Variable

Here is my code:

func animation1() {

UIView.animate(withDuration: 1, animations: {

    // various code

}, completion: { (true) in

    //delay calling the function by the randomDelay value of '0' to '2' seconds
    let randomDelay = arc4random_uniform(3)
    DispatchQueue.main.asyncAfter(deadline: .now() + randomDelay) { // the randomDelay value throws an unresolved identifier 'randomDelay' error
        self.showAnimation2() // Go to the next function
    }
  })
}

Thanks

3 Answers3

6

You need to cast randomDelay to a Double. Then you use it as follows:

let randomDelay = arc4random_uniform(3)
DispatchQueue.main.asyncAfter(deadline: .now() + Double(randomDelay)) {
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • The use of `Double` converts the integer obtained from `arc4random_uniform` into a `Double` which allows you to add the value to `.now()`. You still only add 0, 1, or 2 seconds since that is the only values you will get from your use of `arc4random_uniform`. – rmaddy Jan 03 '18 at 04:21
  • Thanks @rmaddy, works great - is there a way to tweak this to arrive at say 1.5 seconds, or 2.4 seconds, instead of a single whole number? – Server Programmer Jan 03 '18 at 04:28
  • Sure. If you want a number between 0.0 and 3.0 in 1/10 second intervals, change the `3` to `31` and then change `Double(randomDelay)` to `Double(randomDelay) / 10`. This gives you a random number in the range 0 to 30 and the division by 10 gives you values in the range 0.0 to 3.0. – rmaddy Jan 03 '18 at 04:33
4

You did not mention what time unit the random number is in. I suggest you select a unit. For example, seconds:

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(Int(randomDelay)), execute: {...})

Or milliseconds:

DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Int(randomDelay)), execute: {...})
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • The comments in the code in the question states the random number is in seconds. Note that `.seconds` takes an `Int` but `randomDelay` is not an `Int`. – rmaddy Jan 03 '18 at 04:09
  • Yup - when I try the .seconds(randomDelay) it throws aa 'ambiguous' error without more context – Server Programmer Jan 03 '18 at 04:13
  • @ServerProgrammer I edited the code. Forgot that `arc4random_uniform` returns an `UInt32`. – Sweeper Jan 03 '18 at 04:15
1

I think this will help you!

let aRandomVar = 2   // change 2 to desired number of seconds
 let when = DispatchTime.now() + Double(aRandomVar)
    DispatchQueue.main.asyncAfter(deadline: when) {
       // Your code with delay
    }
Madhur
  • 1,056
  • 9
  • 14