Skip to content

Instantly share code, notes, and snippets.

@gnchrv
Last active January 24, 2018 13:17
Show Gist options
  • Save gnchrv/6f6edcb73c350349a2e24ffca5b8f2a4 to your computer and use it in GitHub Desktop.
Save gnchrv/6f6edcb73c350349a2e24ffca5b8f2a4 to your computer and use it in GitHub Desktop.
Swift random(_:) function
// Basically, a wrapper for the standard arc4random_uniform() function
// Helps to get rid of tedious integer type conversions
import UIKit // or any other framework based on Darwin, like Foundation or Darwin itself
func random <T:FixedWidthInteger> (_ upperBound: T) -> Int{
let upperBoundAbs = abs(Int32(upperBound)) + 1 // including this one passed to the function
let randomNumber = Int(arc4random_uniform(UInt32(upperBoundAbs)))
return (upperBound < 0) ? -1 * randomNumber : randomNumber
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment