您可以尝试以下方法。
首先,添加 Fisher-Yates shuffle 的实现(来自 here),以便随机化数组中的元素。
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
}
}
然后使用shuffled()方法对数组中的元素进行随机化,取前五个元素,放入标签中。
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
}
}
// ...
}
您在问题中尝试按顺序访问每个IBOutlets 的操作将不起作用,因为您无法从变量内的值形成标识符。但是,您可以循环访问IBOutlets,如上所示。
附加说明:我已将UILabel 变量的名称从Nr1、Nr2 等更改为nr1、nr2 等。这是因为在Swift 中,UpperCamelCase 应该仅用于类型名称,变量等应使用lowerCamelCase命名。