Last active
July 4, 2016 10:40
-
-
Save akkyie/bedd51e824518e397f7923d6b40d8e50 to your computer and use it in GitHub Desktop.
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 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