This solution leverages shuffled()
and zip()
class MyViewController: UIViewController {
// Add the face buttons to the collection in the storyboard
@IBOutlet var faceButtons: [UIButton]!
let faces = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]
func randomizeFaces() {
// zip() combines faceButtons and faces, shuffled() randomizes faces
zip(faceButtons, faces.shuffled()).forEach { faceButtton, face in
faceButtton.setTitle(face, for: .normal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
randomizeFaces()
}
}
Here is the definition of shuffled()
from: How do I shuffle an array in Swift?
extension MutableCollection where Indices.Iterator.Element == Index {
/// 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)))
guard d != 0 else { continue }
let i = index(firstUnshuffled, offsetBy: d)
swap(&self[firstUnshuffled], &self[i])
}
}
}
extension Sequence {
/// Returns an array with the contents of this sequence, shuffled.
func shuffled() -> [Iterator.Element] {
var result = Array(self)
result.shuffle()
return result
}
}