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
227 views
in Technique[技术] by (71.8m points)

how can I assign the same random number to 2 variables in swift?

I am building an app that the user selects a multiplication table. Then it gives random numbers to multiplicate with the number they select. for example, if the user selects "1". the questions shown would be "1 x 1", or "1 x 8". The problem is that I need to assign the same random number to 2 variables. The one that will be shown on the question and the one used to calculate the result. I thought of something like this, but the random number is different on each variable. What can I do to use the same random number generated on 2 variables?

    func game() -> (String, Int) {
    let randomNumber = multiplicate.randomElement()
    
    switch selectedQuestion {
    case 0:
        return ("1 × (randomNumber!)", 1 * randomNumber!)
    
    default:
        return ("", 0)
    }
}
question from:https://stackoverflow.com/questions/65839354/how-can-i-assign-the-same-random-number-to-2-variables-in-swift

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

1 Answer

0 votes
by (71.8m points)

Not exactly sure what you're asking but you could do something like this:

let number = Int.random(in: 0..<10)

let number2 = number

but I don't think there is a need to create a new variable for this. The whole idea of variables is that you can save some value and then use it later so there isn't really a need to create number2 here.


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

...