Skip to content

Instantly share code, notes, and snippets.

@mmar
Created November 9, 2017 14:53
Show Gist options
  • Save mmar/cd7da5df9653ada129f86cb1dc9aabbc to your computer and use it in GitHub Desktop.
Save mmar/cd7da5df9653ada129f86cb1dc9aabbc to your computer and use it in GitHub Desktop.
Sample a random element from a collection.
extension RandomAccessCollection {
func sample() -> Element {
let random = IndexDistance(arc4random_uniform(UInt32(self.count)))
return self[index(startIndex, offsetBy: random)]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment