Randomly shuffle a Swift array

I just posted a Gist on GitHub that shows how to add a shuffle method to Swift’s Array class, which randomizes the order of an array’s elements. My shuffle method relies on the arc4random function, which means that the file containing that extension method must import the Foundation module. It’s not too efficient, considering it loops over the input array several times, but for a small array it is fast enough.

This code was compiled and tested against Xcode 6 Beta 3.

import Foundation
extension Array
/** Randomizes the order of an array's elements. */
mutating func shuffle()
for _ in 0..<10
sort { (_,_) in arc4random() < arc4random() }
var organisms = [
"ant", "bacteria", "cougar",
"dog", "elephant", "firefly",
"goat", "hedgehog", "iguana"]
println("Original: \(organisms)")
println("Shuffled: \(organisms)")

This entry was posted in Swift and tagged , , . Bookmark the permalink.

3 Responses to Randomly shuffle a Swift array

  1. A good example of the use of underscores. Nice one.

  2. Pingback: Dew Drop – June 19, 2014 (#1800) | Morning Dew

Comments are closed.