Generating random numbers with Xcode 7 and Swift 2

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

  1. BigxMac macrumors newbie

    BigxMac

    Joined:
    Mar 15, 2015
    #1
    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

    abhibeckert

    Joined:
    Jun 2, 2007
    Location:
    Cairns, Australia
    #2
    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)
     
  3. smirk macrumors 6502a

    smirk

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

Share This Page