Skip to content

Instantly share code, notes, and snippets.

@backslash-f
Last active September 7, 2022 09:26
Show Gist options
  • Save backslash-f/487f2b046b1e94b2f6291ca7c7cd9064 to your computer and use it in GitHub Desktop.
Save backslash-f/487f2b046b1e94b2f6291ca7c7cd9064 to your computer and use it in GitHub Desktop.
Swift Clamping Example
import Foundation
import UIKit
/// Clamps the given `value` into the range defined by `minValue` and `maxValue`. For example:
///
/// (0.0 ... 5.0).clamp(4.2) = 4.2
/// (0.0 ... 5.0).clamp(-1.3) = 0.0
/// (0.0 ... 5.0).clamp(6.4) = 5.0
///
/// Source: https://stackoverflow.com/a/46799935/584548
public func clamp<T>(_ value: T, minValue: T, maxValue: T) -> T where T : Comparable {
return min(max(value, minValue), maxValue)
}
struct Bound {
static let lower: CGFloat = 0.0
static let upper: CGFloat = 1.0
}
var progress: CGFloat = 0.0 {
didSet {
//progress = clamp(progress, minValue: Bound.lower, maxValue: Bound.upper)
progress = (Bound.lower ... Bound.upper).clamp(progress)
}
}
progress = 1.2
progress
/// ANOTHER APPROACH ///
extension ClosedRange {
func clamp(_ value: Bound) -> Bound {
return lowerBound > value ? self.lowerBound
: upperBound < value ? self.upperBound
: value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment