I have an array of String
s in Swift 3 (Xcode) and I want to read out 5 random unique elements from it. I'm trying something like this:
class ViewController: UIViewController {
@IBOutlet var Nr1: UILabel!
@IBOutlet var Nr2: UILabel!
@IBOutlet var Nr3: UILabel!
@IBOutlet var Nr4: UILabel!
@IBOutlet var Nr5: UILabel!
myArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
func foo() {
for index in 0..<6 {
let randomNr = Int(arc4random_uniform(UInt32(myArray.count)))
Nr+(index).text = String (randomNr)
}
}
}
But I can't take the iteration index as a placeholder to get Nr1.text
, Nr2.text
, Nr3.text
, etc.
And the next question would be: how do I compare the random items so that they are unique?
Can someone help me out with this?
The way I would do this is to insert them into an arraylist and produce a number between 0 and the size of the list. With this number get and remove that item from the list, and then repeat this process. Each time the size will get smaller and it is impossible to get a non-unique item as you are removing them as you are getting them.