Standard way to “clamp” a number between two values in Swift

Swift 4/5 Extension of Comparable/Strideable similar to ClosedRange.clamped(to:_) -> ClosedRange from standard Swift library. extension Comparable { func clamped(to limits: ClosedRange<Self>) -> Self { return min(max(self, limits.lowerBound), limits.upperBound) } } #if swift(<5.1) extension Strideable where Stride: SignedInteger { func clamped(to limits: CountableClosedRange<Self>) -> Self { return min(max(self, limits.lowerBound), limits.upperBound) } } #endif Usage: 15.clamped(to: 0…10) … Read more

Where can I find the “clamp” function in .NET?

You could write an extension method: public static T Clamp<T>(this T val, T min, T max) where T : IComparable<T> { if (val.CompareTo(min) < 0) return min; else if(val.CompareTo(max) > 0) return max; else return val; } Extension methods go in static classes – since this is quite a low-level function, it should probably go … Read more