Skip to content

Instantly share code, notes, and snippets.

@Azoy
Created November 16, 2017 04:14
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 Azoy/30d2554d11a3fb8f770e3b310fb47aca to your computer and use it in GitHub Desktop.
Save Azoy/30d2554d11a3fb8f770e3b310fb47aca to your computer and use it in GitHub Desktop.
Randomizable Potential
struct Date : Randomizable, Strideable {
typealias Stride = Int
let timestamp: UInt32
static func random<T: RandomNumberGenerator>(using generator: T) -> Date {
return Date(timestamp: (0 ... UInt32.max).random!)
}
func distance(to other: Date) -> Int {
return Int(other.timestamp) - Int(self.timestamp)
}
func advanced(by n: Int) -> Date {
return Date(timestamp: UInt32(Int(self.timestamp) + n))
}
}
struct Color : Randomizable, Strideable {
typealias Stride = Int
let value: UInt32
static func random<T: RandomNumberGenerator>(using generator: T) -> Color {
return Color(value: (0 ... 0xFFFFFF).random!)
}
func distance(to other: Color) -> Int {
return Int(other.value) - Int(self.value)
}
func advanced(by n: Int) -> Color {
return Color(value: UInt32(Int(self.value) + n))
}
}
extension Array
where Element: Randomizable & Strideable, Element.Stride: SignedInteger {
init(randomElements: Int, in bounds: CountableRange<Element>) {
self = (0 ..< randomElements).map { _ in bounds.random! }
}
init(randomElements: Int, in bounds: CountableClosedRange<Element>) {
self = (0 ..< randomElements).map { _ in bounds.random! }
}
}
let dateRange = Date(timestamp: 100) ..< Date(timestamp: 1000)
print([Date](randomElements: 10, in: dateRange))
let colorRange = Color(value: 0x0000FF) ... Color(value: 0xFF0000)
print([Color](randomElements: 10, in: colorRange))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment