You could try something like the following.
First, add this implementation of a Fisher-Yates shuffle (from here) in order to randomise the elements in the array.
extension MutableCollection {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
let i = index(firstUnshuffled, offsetBy: d)
swapAt(firstUnshuffled, i)
}
}
}
extension Sequence {
/// Returns an array with the contents of this sequence, shuffled.
func shuffled() -> [Element] {
var result = Array(self)
result.shuffle()
return result
}
}
Then use the shuffled()
method to randomise the elements in the array, take the first five elements, and put them into the labels.
class ViewController: UIViewController {
// ...
let myArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
func foo() {
// Take the array and shuffle it.
let shuffled = self.myArray.shuffled()
// Slice the first five elements.
let randomElements = shuffled[0..<5]
// Build an array that contains all the labels in order.
let outlets = [self.nr1, self.nr2, self.nr3, self.nr4, self.nr5]
// Loop through the randomly chosen elements, together with their indices.
for (i, randomElement) in randomElements.enumerated() {
// Put the random element at index `i` into the label at index `i`.
outlets[i]?.text = randomElement
}
}
// ...
}
What you're trying to do in your question to access each of the IBOutlet
s in order won't work, because you can't form an identifier from the value inside a variable. However, you can loop through the IBOutlet
s as shown above.
Additional note: I've changed the names of your UILabel
variables from Nr1
, Nr2
, etc. to nr1
, nr2
, etc. This is because in Swift, UpperCamelCase
should be used only for type names, and variables etc. should be named using lowerCamelCase
.