2017-07-11 71 views
-1

我有这样的代码:六个随机数字,但重复?怎么不重复?斯威夫特

import UIKit 

class ViewController: UIViewController { 
    @IBAction func geraNumeros(_ sender: Any) { 
     var numeroAleatorio:[Int] = [] 

     for _ in 1...6 { 
      numeroAleatorio.append(Int(arc4random_uniform(60)+1)) 
     } 

     numeroAleatorio.sort() 

     labelNumeros.text = "\(numeroAleatorio[0]) - \(numeroAleatorio[1]) - \(numeroAleatorio[2]) - \(numeroAleatorio[3]) - \(numeroAleatorio[4]) - \(numeroAleatorio[5]) " 

    } 

    @IBOutlet weak var labelNumeros: UILabel! 
} 

但有时号码重复,如:

10 - 18 - 12 - 10 - 30 - 60

10-10一样,所以做什么?

+1

有时随机产生的数字重复。考虑你扔掷骰子的时间;你不能保证每次都有不同的号码。 –

+0

https://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift可能是你在找什么。 –

+0

或者:https://stackoverflow.com/questions/27541145/how-to-generate-a-random-number-in-swift-without-repeating-the-previous-random-n。 –

回答

0

在将值附加到数组之前,使用.contains()函数检查数组是否已经存在于您的数组中。如果存在,继续循环,直到我们有我们需要的6个元素。

为此,您必须更改您的循环以保持循环,直到找到6个有效元素。

喜欢的东西

while numeroAleatorio.count < 6