[英]How not repeat Switch cases? (Swift)
我在做測驗游戲。 我在交換機的每個“案例”中都預訂了所有問題及其答案。 我希望以隨機順序選擇大小寫,但是當人們回答問題並按下“下一步”按鈕后,功能“ randomQuestions”再次起作用,但是我不希望重復前面使用的相同大小寫。
func randomQuestions ()
{
var randomNumber = arc4random_uniform(3)
while previousNumber == randomNumber
{
randomNumber = arc4random_uniform(3)
}
previousNumber = randomNumber
switch(randomNumber)
{
case 0:
textoHideUnhide()
questionsLabel.text = "What color is the sun?"
button1.setTitle("Yellow", forState: UIControlState.Normal)
button2.setTitle("Black", forState: UIControlState.Normal)
button3.setTitle("Blue", forState: UIControlState.Normal)
button4.setTitle("White", forState: UIControlState.Normal)
correctAnswer = "1"
break
case 1:
textoHideUnhide()
questionsLabel.text = "What color is the moon?"
button1.setTitle("Red", forState: UIControlState.Normal)
button2.setTitle("Blue", forState: UIControlState.Normal)
button3.setTitle("White", forState: UIControlState.Normal)
button4.setTitle("Orange", forState: UIControlState.Normal)
correctAnswer = "3"
break
case 2:
textoHideUnhide()
questionsLabel.text = "What color is the grass?"
button1.setTitle("White", forState: UIControlState.Normal)
button2.setTitle("Green", forState: UIControlState.Normal)
button3.setTitle("Orange", forState: UIControlState.Normal)
button4.setTitle("Red", forState: UIControlState.Normal)
correctAnswer = "2"
break
default:
break
}
為了避免多次出現相同的隨機數,可以創建一個包含問題編號的數組,然后將其隨機排列。
var indices = [0, 1, 2]
for i in 0 ..< indices.count {
var temp = indices[i]
var j = arc4random_uniform(indices.count)
indices[i] = indices[j]
indices[j] = temp
}
第一個問題是在indices[0]
處提供數字的問題,當用戶單擊下一步時,您在indices[1]
處提問,依此類推。
您必須將變量previousNumber
作為全局(實例)變量放在方法之外
var previousNumber = UInt32.max // declare the variable with an "impossible" value
func randomQuestions()
{
var randomNumber : UInt32
do {
randomNumber = arc4random_uniform(3)
} while previousNumber == randomNumber
previousNumber = randomNumber
switch(randomNumber) {
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.