Home » Swift Range Operators

Swift Range Operators

by Online Tutorials Library

Range Operators

Swift 4 supports several types of range operators which are used as shorthand for expressing a range of values.

  • Closed Range Operators
  • Half-Open Range Operator
  • One Sided Ranges

Closed Range Operator

The closed range operator (a…b) specifies the range between a and b (here a and b inclusive and value of a should not be greater than value of b). The closed range operator is useful when you have to iterate over a range in which you want all of the values to be used, such as with a for-in loop.

Example:

Output:

1 times 5 is 5  2 times 5 is 10  3 times 5 is 15  4 times 5 is 20  5 times 5 is 25  6 times 5 is 30  7 times 5 is 35  8 times 5 is 40  9 times 5 is 45  10 times 5 is 50  

Half-Open Range Operator

The half-open range operator (a..<b) specifies a range between a to b, but it doesn?t include b. It is called half-open range operator because it contains its first value, but not its final value. Similarly as closed range operator, the value of a must not be greater than b in half-open range operator also. If the value of a is equal to b, then the resulting range will be empty.

Half-open range operator is generally used with arrays where it counts the length of the list.

Example:

Output:

Person 1 name is Albert  Person 2 name is Aryan  Person 3 name is Ajeet  Person 4 name is Jill  

One Sided Ranges

One sided ranges operator is an alternative form of closed range operator or half-open range operator in one direction only.

Example1:

Output:

Ajeet  Jill  

Example2:

Output:

Albert  Aryan  Ajeet  

Example3:

Output:

Albert  Aryan  

You may also like