Swift enum range matching

I have been recently working on a HealthKit related app, where I wanted to categorise the blood pressure data. If you are not familiar with this data, here is a little explanation:

Measuring Blood pressure

Blood pressure build up from 2 numbers: the systolic value and the diastolic value. The valid value ranges for systolic and diastolic are different, actually the Apple Health App only allows you to input a number between 40…300 for systolic, and between 30…200 for the diastolic value. The normal value is 120/80.  There are different scales and ranges around the world to define the ranges and their actual meaning, but actually the highest range from the aforementioned two values will determine the quality in other words how high is your blood pressure.

You can see from that classification is crying for an enum, so I came up with this for the systolic ranges classification:

So far so good. Now, let’s add the respective ranges:

Boomer!

You’ve got:

Raw value for enum case must be a literal.

You can not assign ranges to enum cases. In the other hand we can declare variables inside an enumeration. Have you noticed it?

As you will see you can still reference to those static constants, like it would be one case of enum. I am adding the ranges for the Diastolic values, and also defining the final classification for the actual blood pressure:

Matching the range

We are ready with the constants. Now we need to figure out how to express based on the systolic and diastolic values that in which classification has the given blood pressure? The switch statement combined with a tuple makes the pattern matching quite easy (I have the idea from Paul Hudson’s Pro Swift book, worth to read it ;)). I just combined the systolic and diastolic values into a tuple, and starting from the highest value, checking only with one of the pairs as it follows:

Based on our discussion on reddit, actually there is a small trick with the switch cases, were instead of using the fallthrough , you can just add te different cases with the comma (thanks for the tip u/flippant_gibberish), like this:

I hope I could give you some hints how to use ranges with enums. Please, feel free to share your thoughts!


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.