Created
March 14, 2016 14:56
-
-
Save mangar/6eb9d42b2fdfaf70bc38 to your computer and use it in GitHub Desktop.
Shuffle an array - Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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