0

So I'm trying to generate a random number between negative and positive range because I need to give an object a position on the x axis. I've tried with arc4random and arc4random_uniform but it doesn't work. I need a way to generate a random position on the x axis, negative and positive.

  • https://stackoverflow.com/questions/34712453/how-to-generate-a-random-number-in-a-range-10-20-using-swift You can use the extension at the duplicate question and use a range with a negative lowerbound `(-10...10).random` – Leo Dabus Feb 26 '18 at 21:16

2 Answers2

1

I don't think you can generate negative random number using arc4random directly

let lValue = -10 // (your negative number)
let uValue = 10 //(your positive number)
let result = Int(arc4random_uniform(UInt32(uValue - lValue + 1))) +   lValue

print(result) 

hope this will work

Iraniya Naynesh
  • 1,125
  • 3
  • 14
  • 26
1
let min : UInt32 = 10
let max : UInt32 = 50
let randomNumber = arc4random_uniform(max - min) + min

if arc4random_uniform(2) == 0 {
    randomNumber = randomNumber * -1
}
Kárpáti András
  • 1,221
  • 1
  • 16
  • 35