Swift range in if statement

March 19, 2016

Swift range in if statement

We are all familiar with the Swift's range operator, that looks like i...n or i..<n like. And we also do know how to use if statements. Yet we have never before combined them together. Well, at least I haven't yet.

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!

Comments

comments powered by Disqus