Adis
Adis
Aug 6 · 1 min read

Sometimes, especially when dealing with offsets in UIScrollViews or other, we need to clamp a certain undefined range of numbers into another defined array of numbers.

A good example when needing this would be an automatic show/hide of a header (alpha or offset) depending on the offset of an unknown size UITableView.

You could go about solving this in an imperative way, for example:

This looks a bit clunky, so, you might feel inclined to make this a bit more elegant and shorter, like:

However, why simply not leverage Swift and functional paradigm to make this reusable, elegant and easy to read?

For starters, let’s extend a few protocols, the ones we’re interested in are Comparable (stuff that can be ordered) and Strideable (stuff that can be counted):

Now, using the method above would simply end up as:

Happy coding!

Swift bits is a series of posts designed to improve your Swift and Cocoa skills while keeping it as concise and easy as possible. Stay tuned for more quality iOS content!

Capsized Eight

Design, Development, Programming. Dogs, Champagne Sabering, Animal print.

Adis

Written by

Adis

Nerd gone rogue.

Capsized Eight

Design, Development, Programming. Dogs, Champagne Sabering, Animal print.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade