0

I was wondering if this is the best way to generate a random number in Swift.

This is what I have thought of thus far:

var randomNumber:Int = random() * 100 + 1 //What value does this return? 

I was wondering if this is a viable 1 - 100 range in Swift utilizing the random() function? I am unsure if this is. I have not dealt with random numbers much in Swift 2. However in Java, the equivalent would be Math.random() * 100 + 1

I'm curious to know what would be the equivalent of this in Swift 2. Thanks in advance!

2
  • @EricD. yes, I flagged it but it didn't auto-generate the comment for some reason Commented Jan 31, 2016 at 22:38
  • @originaluser2 I think it doesn't when it detects a comment with the link already in it, and there was one at this moment. Commented Jan 31, 2016 at 22:39

1 Answer 1

-1
let random = Int(arc4random_uniform(100) + 1) 

+ 1 since arc4random_uniform generates a random number between 0 and the parameter - 1

Sign up to request clarification or add additional context in comments.

4 Comments

really? do we need 2 virtually identical answers on a question that's a duplicate anyway?
Are you sure this still works in the latest iteration of XCode and Swift? I do not see this option anymore in Xcode.
@Linuxn00b you have to import the Darwin module (as stated in the duplicate question)
@originaluser2 it seems to work without the Darwin module. Thanks for all your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.