Skip to content

Instantly share code, notes, and snippets.

@mangar
Created March 14, 2016 14:56
Show Gist options
  • Select an option

  • Save mangar/6eb9d42b2fdfaf70bc38 to your computer and use it in GitHub Desktop.

Select an option

Save mangar/6eb9d42b2fdfaf70bc38 to your computer and use it in GitHub Desktop.
Shuffle an array - Swift
import Foundation
extension Array {
func shuffle() -> Array {
var result = Array(self)
result.shuffleInPlace()
return result
}
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])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment