You may have learned how enums are best used with switch from the previous articles, but wondered how the switch
statement handles matching cases with a specific range or interval.
In Swift, you can create a range of values as a switch case
using the built-in range operators.
A great example of it would be handling the response code from a network call. The response code is a number for a standard HTTP code.
switch response.code { case 200...299: print("Success") case 400...599: print("Failed") default: print("Unsupported") }
If the response.code
falls to a value within the range of 200 to 299, then the switch
statement will print "Success".
If the code falls to a value within the range of 400 to 599, then the switch
statement will print "Failed", since that code pertains to either a client-side or a server-side error.
Otherwise, it will print "Unsupported".
That’s all for this post. See you at the next one!