How to clamp a number between two values in Swift

The breadth and depth of Apple’s Foundation framework is truly impressive, and it’s surprising when a common utility is missing from it. One such function I’ve found myself needing to write again and again over the years is clamped(), which limits a number to a minimum and maximum value. (For example, calling 11.clamped(to: 1...10) would return 10 because 11 exceeds the maximum value.)

When I was doing more manual layout of things like UITableView and UICollectionView cells, I would often need to use this function to make sure the content inside of my cells wasn’t too small or too big. Even today, when most layout is handled by Auto Layout or SwiftUI, I still need to reach for clamped() occasionally. In fact, I found myself needing it yesterday. Instead of just adding it directly to the codebase I was working in, I decided it would be better to create a simple Swift Package I could use from now on in whatever codebase I wanted. The result is Clamp. I open-sourced it because, even though clamped() is a simple function to write, I’m guessing I’m not the only Swift developer who doesn’t want to write it again.

Clamp is easy to use (it better be!), and it’s MIT-licensed, so feel free to use it in any of your public, private, or commercial projects.

// immutable version
5.clamped(lowerBound: 1, upperBound: 10) // returns 5
0.clamped(lowerBound: 1, upperBound: 10) // returns 1
11.clamped(lowerBound: 1, upperBound: 10) // returns 10

5.clamped(to: 1...10) // returns 5
0.clamped(to: 1...10) // returns 1
11.clamped(to: 1...10) // returns 10

// mutable version
var number = 5
number.clamp(to: 1...10) // no change
number.clamp(to: 1...4) // `number` is changed to 4
number.clamp(to: 10...20) // `number` is changed to 10

Be sure to let me know if you have any thoughts or use Clamp to build something cool…or, you know, if you are angry at me for trying to change the Swift ecosystem into the JavaScript ecosystem—full of millions of tiny, single-purpose libraries.