Skip to content

Instantly share code, notes, and snippets.

@ptsakyrellis
Created March 14, 2016 21:14
Show Gist options
  • Save ptsakyrellis/e9571e0180f359f5a98b to your computer and use it in GitHub Desktop.
Save ptsakyrellis/e9571e0180f359f5a98b to your computer and use it in GitHub Desktop.
CollectionType and MutableCollectionType extensions to be able to easily shuffle items
/**
CollectionType and MutableCollectionType extensions to be able to easily shuffle
items
*/
import Foundation
extension CollectionType {
/// Return a copy of "self" with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
extension MutableCollectionType where Index == Int {
/// Shuffle the elements of "self" in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
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