Swift Range Operators

2 min readDec 3, 2021

--

Range Operator in Swift is a basic operator that is used to operate over a range. There are multiple types of range operators where we can include or exclude the upper range. Or we can start the range with some value or can end before some max value.

`This post was originally posted at https://agrawalsuneet.github.io/blogs/swift-range-operators/ and reposted on Medium on 03rd Dec 2021.`

The range operators can be used with for loops, if conditions, switch conditions or even in array iteration. First, let to see a basic example of a range operator.

A basic range operator can be defined with … having a lower range value to the left side and upper range value to the right side of …

`//For-in loopfor pos in 0...5 {    print(pos)}//If conditionif (0...5).contains(value){    print("between 0 to 5")}//Switch operatorlet value = 5switch(value){case 0...5:    print("between 0 to 5")default:    print("less than 0 or greater than 5")}//Array iterationlet numbers = ["One", "Two", "Three", "Four", "Five"]for number in numbers[1...3] {    print(number)}`

Now that we understood the very basic use cases of the range operators, let’s try to understand its types.

There are 3 types of range operators

1. Closed Range Operator
2. Half-Open Range Operator
3. One-Sided Range Operator

Please continue reading at https://agrawalsuneet.github.io/blogs/swift-range-operators/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.