Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

swift - How does one make random number between range for arc4random_uniform()?

so my goal in this codebit is to randomly roll two dice and as we all know your regular die only has 6 sides so I imported Foundation for access to arc4random_uniform(UInt32). I attempted using the range of (1..7) to avoid randomly getting 0 however that returned an error which I didn't enjoy too much. I tried to do this:

dice1 = arc4random_uniform(UInt32(1..7))

however that returned

Could not find an overload for 'init' that accepts the supplied arguments

I hope that this is enough information for you amazing debs out there to help me :)

Please note I am just doing this in a playground to practice swift. It isn't imperative that I learn how to do this; it's just me tinkering before I jump into building actual apps :D

//imports random number function
import Foundation
//creates data storage for dice roll
var dice1: UInt32 = 0
var dice2: UInt32 = 0
//counter variable
var i = 0
//how many times snake eyes happens
var snakeeyes = 0
 //how many times a double is rolled
var `double` = 0
//rolls dice 100 times
while i < 100{
    //from here
    //sets dice roll

This returns an error of 'Range $T3' is not convertible to UInt32

   dice1 = arc4random_uniform(1..7)
   dice2 = arc4random_uniform(1..7)
    //checks for snake eyes
    if dice1 == 1 && dice2 == 1 {
        snakeeyes = snakeeyes + 1

    }
    //checks for doubles
    if dice1 == dice2{
        `double` = `double` + 1
    }
    //increases counter
        i = i + 1
    //to here
}
println("You got Snake Eyes (snakeeyes) times.")
println("You got Doubles, (`double`) times.")
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe you should do

dice1 = arc4random_uniform(6) + 1;

to get the range 1 - 6. I don't do iOS objective C nor have I any knowledge on swift-language though. The random method should return a value between 0 and 5, and + 1 will make it a value between 1 and 6.

If you need a range between lets say 10 - 30 then just do

int random = arc4random_uniform(21) + 10;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...