Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

BigxMac

macrumors member
Original poster
Mar 15, 2015
35
13
I need to generate a random number and am using Xcode 7 beta with Swift 2. It appears the arc4random function no longer exists as well as the arc4random_uniform function. The options I have are arc4random_stir(), arc4random_buf(UnsafeMutablePointer<Void>, Int), and arc4random_addrandom(UnsafeMutablePointer<UInt8>, Int32). I can't find any docs on the functions and no comments in the header files give hints. Any help is appreciated
 
arc4random() wasn't very good anyway, you should always have been using arc4random_buf.

It accepts a pointer to a location in memory, and a length for how much memory to overwrite with random data.

So define a variable, and give arc4random_buf the location in memory of that variable and a count of how many bytes the variable takes up:

Code:
var randomNum: UInt = 0
arc4random_buf(&randomNum, sizeof(UInt))

If you want a min/max value, then use the modulus operation:

Code:
func rand(min: UInt, max: UInt) -> UInt
{
  var randomNum: UInt = 0
  arc4random_buf(&randomNum, sizeof(UInt))

  return min + (randomNum % (max - min))
}

let blah = rand(10, 20)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.