Swift range in if statement
March 19, 2016
We are all familiar with the Swift's range operator, that looks like
Let's take the code number that we get from the server as a response. It can be a 201, 404, 400, 500 and so on. When we need to check whether we have a successful request, we need to check this code. What would one do in this situation, most likely, is this:
if statusCode >= 200 && statusCode <= 299 {
// do something
}
Well, this doesn't look much like Swift-styled way of doing things. What is not obvious, is that we are able to use this range operator here instead. We could combine our well-knowed range operator and put it inside the if statement like this:
if case 200 ... 299 = statusCode {
// do something
}
Not only it looks more "Swifty", it moves us away from the C-styled coding we are all got used to in Objective-C.
Hope this was new to someone as it was for me. Happy coding!