Skip to content

Instantly share code, notes, and snippets.

@fewlinesofcode
Last active January 25, 2017 12:41
Show Gist options
  • Save fewlinesofcode/84385d9bb450e797b2e4b5478d4f8476 to your computer and use it in GitHub Desktop.
Save fewlinesofcode/84385d9bb450e797b2e4b5478d4f8476 to your computer and use it in GitHub Desktop.
Swift implementation of Haskell `Bounded` type
/// Sometimes we need to limit values
/// For instance, you are making application for the Tour De France, and
/// You have a variable depicting the Climb category (1..5)
/// Here is the place, where `Bounded` can be used
struct Bounded<T: Comparable> {
var minimum: T
var maximum: T
var value: T? {
willSet {
if let val = newValue {
assert(val >= minimum && val <= maximum, "Error! `value` is out of bounds!")
value = val
}
}
}
init(min: T, max: T, val: T? = nil) {
assert(min <= max, "Error! `min > max` or `max < min`")
minimum = min
maximum = max
value = val
}
}
/// Usage
/// let a = Bounded(min: 10, max: 20, val: 12)
/// var b = Bounded(min: 0, max: 3)
/// b.value = 3
/// b.value = 2
/// b.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment