Skip to content

Instantly share code, notes, and snippets.

@mathewsanders
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathewsanders/82311409978066b02932 to your computer and use it in GitHub Desktop.
Save mathewsanders/82311409978066b02932 to your computer and use it in GitHub Desktop.
Calculate a random delay for animation
// Playground - noun: a place where people can play
// Running in Xcode6-Beta5
import UIKit
var delay : NSTimeInterval
// best appraoch: use arc4random_uniform (benefit you don't have to seed rand())
delay = NSTimeInterval(arc4random_uniform(900)+100) / 1000
// original calculation
// -> 0.0
delay = NSTimeInterval( ((Int(rand()) % 900)+100.0) / 1000.0)
// cast to Double
// -> 0.449
delay = NSTimeInterval( ((Double(rand()) % 900)+100.0) / 1000.0)
// just the NSTimeInterval(Double) cast
// -> 0.573
delay = NSTimeInterval(rand() % 900 + 100) / 1000
@dactrtr
Copy link

dactrtr commented Aug 11, 2014

when i use the original code i get a error:
"could not find a overload for '/' that accepts the supplied arguments"
so i changed the Int() for a Double(), and it work magic sound now im gonna test without it

@mathewsanders
Copy link
Author

@dactrtr I'm at work now and seeing that the Int cast is returning 0.0, I think when I wrote this at home I was on an earlier release beta and now something has changed.

Using Beta-5 right now delay = NSTimeInterval(rand() % 900 + 100) / 1000 seems to be working great for me!

TBH I'm making a bunch of mistakes with casting in Swift :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment