Swift version: 5.6
Modern Swift code will use Swift’s own shuffle()
and shuffled()
methods, but sometimes you might find code that does it by hand using arc4random_uniform()
or similar.
Nate Cook wrote a simple shuffle()
extension to arrays that implements the Fisher-Yates shuffle algorithm in Swift. Here's the code:
extension Array {
mutating func customShuffle() {
for i in 0 ..< (count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
swapAt(i, j)
}
}
}
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Available from iOS 2.0 – see Hacking with Swift tutorial 35
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.