Skip to content

Instantly share code, notes, and snippets.

@akkyie
Last active July 4, 2016 10:40
Show Gist options
  • Save akkyie/bedd51e824518e397f7923d6b40d8e50 to your computer and use it in GitHub Desktop.
Save akkyie/bedd51e824518e397f7923d6b40d8e50 to your computer and use it in GitHub Desktop.
import Foundation
extension Array {
func random() -> Element {
return self[Int(arc4random_uniform(UInt32(self.count)))]
}
}
struct Dice<T> {
let faces: [T]
init(_ first: T, _ second: T, _ others: T...) {
self.faces = [first, second] + others
}
func roll() -> T {
return faces.random()
}
func roll() -> T? {
let optionalFaces = faces.map { Optional.Some($0) } + [Optional.None]
return optionalFaces.random()
}
}
extension Dice where T: ForwardIndexType {
init(_ range: Range<T>) {
self.faces = [T](range)
}
}
let dice = Dice(1 ... 6)
for i in 0 ..< 100 {
print(dice.roll() as Int)
}
let names = Dice("Alice", "Bob", "Charlie")
for i in 0 ..< 100 {
print(names.roll() ?? "nobody")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment