Mobile App Development Blog

Blog Home

Swift 3.0 – Range Operators

November 22, 2016

Disclaimer: This post is for my friends who don’t flinch at the mere mention of ‘code’. This is an intro to help you understand the concept of range operators in Swift.

swift-range-operators

Range Operators:

In order to avoid traditional way of iterating through a range of values, Swift introduced handy range operators to improve several capabilities and avoid common coding mistakes. Swift has two types of range operators to reach a range of values. These are shorthand to avoid traditional way of iterating through values using for loop etc.

Traditional Iteration:

for (var i = 0; i<=5;i += 1) {

print(“index \(i)”)

}

The two types of range operator in swift are:

  1. 1. Closed Range Operator  (a … b) – range includes a and b.
  2. 2. Half – Open Range Operator (a ..< b ) range includes a only.
  1. Closed Range Operator – This operator defines as (x … z) values from x to z. In this range of values both ‘x’ and ‘z’ are included in the range. But, value ‘x’ must not be greater than value of ‘z’. If the value of ‘x’ is greater than ‘z’, the compiler will throw an error. If ‘x’ and ‘z’ are same, it will run successfully.

Example:

(a)

for i in 0 … 5 {

print(“index \(i)”)

}

Output:

index 0

index 1

index 2

index 3

index 4

index 5

(b)

for i in 0 … 0 {

print(“index \(i)”)

}

Output:

index 0

As you can see both it includes ‘0’ and ‘5’.

  1. Half – Open Range Operator – This operator defines as (x … z) values from x to z. In this range of values ‘x’ will include only. It called as Half Open because it will include only x, but not it’s final value.

Note: If ‘x’ and ‘z’ will be equal then resulting range will have no values (empty).

Example: Just adding very simple e. g.

(a)

for i in 0 ..< 5 {

print(“index \(i)”)

}

Print:

index 0

index 1

index 2

index 3

index 4

(b)

for i in 0 ..< 0 {

print(“index \(i)”)

}

Print:

As you can see (a) it includes ‘0’ only.

Hope this gives you clarity. If you have doubts or technical questions on this topic, feel free to comment and our geek squad will be there for rescue.

About the author

Sanoj Kumar Kashyap is a senior iOS developer who believes that developing app for any device is always fun. He has mostly worked for iPhone and is eager to jump to other device platforms. He is also an ardent fan of photography, gaming and cooking.

Posted Under: