Last active
January 24, 2018 13:17
-
-
Save gnchrv/6f6edcb73c350349a2e24ffca5b8f2a4 to your computer and use it in GitHub Desktop.
Swift random(_:) function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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