简体   繁体   中英

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)
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM