0

I have an extension for generating random CGFloats in Swift:

public extension CGFloat {
    /// Randomly returns either 1.0 or -1.0.
    public static var randomSign:CGFloat {
        get {
            return (arc4random_uniform(2) == 0) ? 1.0 : -1.0
        }
    }
    /// Returns a random floating point number between 0.0 and 1.0, inclusive.
    public static var random:CGFloat {
        get {
            return CGFloat(arc4random())
        }
    }
    /**
     Create a random num CGFloat

     - parameter min: CGFloat
     - parameter max: CGFloat

     - returns: CGFloat random number
     */
    public static func random(min: CGFloat, max: CGFloat) -> CGFloat {
        return CGFloat.random * (max - min) + min
    }
}

and I'm using it like this:

var viewHeight:CGFloat = view.frame.size.height

    var randomY:CGFloat = CGFloat.random(min: 0, max: viewHeight)
    print(randomY)


    var randomWidth:CGFloat = CGFloat.random(min: 90, max: 300)

    print(randomWidth)

but I'm getting strange results, like:

6483772455.0
878524470690.0

why so? I expected to have much lower values, e.g. between 90-300, etc.

What did I do wrong?

Hamish
  • 78,605
  • 19
  • 187
  • 280
user3766930
  • 5,629
  • 10
  • 51
  • 104
  • `arc4random()` returns a random `UInt32` – not a value between 0 and 1. – Hamish Mar 18 '17 at 23:32
  • @Hamish how can I get a random CGFloat then? I want to have a random number that I could later use in: `CGRect.init(x: 0, y: randomY, width: randomWidth, height: 20)` – user3766930 Mar 18 '17 at 23:33
  • Divide by `UInt32.max` – see for example http://stackoverflow.com/a/33078096/2976878 (they use the old `UINT32_MAX` Darwin constant, but it's the same thing). – Hamish Mar 18 '17 at 23:37
  • Well ok, that worked :) do you bother to post it as an answer or should I close this question? – user3766930 Mar 18 '17 at 23:41
  • Hmmm... I think it's probably okay just to close as a dupe of http://stackoverflow.com/q/25050309/2976878, as [this answer there](http://stackoverflow.com/a/28075467/2976878) does exactly what you want. – Hamish Mar 19 '17 at 00:04

0 Answers0