Generating random numbers with Xcode 7 and Swift 2

Discussion in 'iOS Programming' started by BigxMac, Sep 13, 2015.

  1. BigxMac macrumors newbie


    Mar 15, 2015
    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
  2. abhibeckert macrumors regular


    Jun 2, 2007
    Cairns, Australia
    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:

    var randomNum: UInt = 0
    arc4random_buf(&randomNum, sizeof(UInt))
    If you want a min/max value, then use the modulus operation:

    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)
  3. smirk macrumors 6502a


    Jul 18, 2002
    Orange County, CA
    I've been using arc4random_uniform in my Swift projects just fine. You need to import Foundation, though.

Share This Page