How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in o
This is a version of Nate's implementation of the Fisher-Yates shuffle for Swift 4 (Xcode 9).
extension MutableCollection {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
for i in indices.dropLast() {
let diff = distance(from: i, to: endIndex)
let j = index(i, offsetBy: numericCast(arc4random_uniform(numericCast(diff))))
swapAt(i, j)
}
}
}
extension Collection {
/// Return a copy of `self` with its elements shuffled
func shuffled() -> [Element] {
var list = Array(self)
list.shuffle()
return list
}
}
The changes are:
Indices.Iterator.Element == Index
is now part
of the Collection
protocol, and need not be imposed on the
extension anymore.swapAt()
on the collection,
compare SE-0173 Add MutableCollection.swapAt(_:_:).Element
is an alias for Iterator.Element
.