Skip to content

Instantly share code, notes, and snippets.

@mklbtz
Last active November 3, 2018 17:33
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 mklbtz/080c311fb3030ada8b06b269d69c8e78 to your computer and use it in GitHub Desktop.
Save mklbtz/080c311fb3030ada8b06b269d69c8e78 to your computer and use it in GitHub Desktop.
Implements "random" properties for collections and ranges
import Darwin
extension RandomAccessCollection {
// Fails if collection is larger than UInt32.max
var randomIndex: Index {
guard !isEmpty else { return endIndex }
let fullDistance = UInt32(distance(from: startIndex, to: endIndex))
let randomDistance = IndexDistance(arc4random_uniform(fullDistance))
return index(startIndex, offsetBy: randomDistance)
}
var random: Element? {
let index = randomIndex
if index == endIndex {
return nil
} else {
return self[index]
}
}
}
// Preconditions: these should always hold
[].randomIndex == 0 // true
[1].randomIndex == 0 // true
[1,2][1...].randomIndex == 1 // true
[1,2][2...].randomIndex == 2 // true
(0 ..< UInt32.max).randomIndex != Int(UInt32.max) // true
(0 ... UInt32.max).count > Int(UInt32.max)
//(0 ... UInt32.max).randomIndex // Failure: not enough bits for signed value
// Example usage: what should I eat tonight?
print(Array("πŸŒ­πŸ•πŸŒ―πŸ—πŸπŸœπŸ£πŸ›πŸΊπŸ³").random)
@mklbtz
Copy link
Author

mklbtz commented Sep 3, 2017

Requires Swift 4

@mklbtz
Copy link
Author

mklbtz commented Nov 3, 2018

This is now redundant, thanks to the new random APIs in Swift 4.2!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment