Last active
November 3, 2018 17:33
-
-
Save mklbtz/080c311fb3030ada8b06b269d69c8e78 to your computer and use it in GitHub Desktop.
Implements "random" properties for collections and ranges
This file contains 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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires Swift 4