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)") | |
organisms.shuffle() | |
println("Shuffled: \(organisms)") |
A good example of the use of underscores. Nice one.
Thanks Colin.
Pingback: Dew Drop – June 19, 2014 (#1800) | Morning Dew