Skip to content

Instantly share code, notes, and snippets.

@maximbilan
Last active September 15, 2015 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maximbilan/4e1f5e63946b1559af8d to your computer and use it in GitHub Desktop.
Save maximbilan/4e1f5e63946b1559af8d to your computer and use it in GitHub Desktop.
Swift Array Shuffle
import Foundation
extension CollectionType where Index == Int {
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
extension MutableCollectionType where Index == Int {
mutating func shuffleInPlace() {
if count < 2 {
return
}
for i in 0..<count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
// Using
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.shuffleInPlace()
print(array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment