Swift range operators

There are two types of range operators in Swift latest language.

  • Closed range operator
  • Half-open range operator
  • One side range operator

Range operators are a shorthand way of representing a range of values in array manipulation.

These are applied with two operands.

Syntax

operand1 rangeoperator operand2

swift Closed range operator

These are represented with three dot symbols between operands as given below

start...end

Notes:

  • start always greater than the end value
  • start and end value is included
  • if the start and end are equal, return a single value

The above syntax includes values from a to be inclusive of a and b.

here the value of a should always be greater than equal to b.

var words = ["1", "2", "3", "4","5","6"]
// index starts from 1 to 3
print(words[1...3])//["2", "3", "4"]
// index starts from 1 to 1.
print(words[1...1])//["2"]

Below operator throws an Swift/ClosedRange.swift:347: Fatal error: Range requires lowerBound <= upperBound

print(words[3...1])

Swift Half open range operators

This also contains a range of values with the end value excluded. half range means only the first start value is included and end value is excluded

start..<end

Notes:

  • start always greater than the end value
  • end value is excluded
  • if start and end are equal, returns empty

Here is an example

var words = ["1", "2", "3", "4","5","6"]
print(words[1..<3]) //["2", "3"]
print(words[1..<1]) //[]
print(words[3...1]) //  compile error Swift/ClosedRange.swift:347: Fatal error: Range requires lowerBound <= upperBound

Swift one-side range operator

In this, One side of the range operator is not defined. These have all been defined and working since the Swift 4 versions.

[start]...[end]

one of the values either start or end is not declared

Here is an example

var words = ["1", "2", "3", "4","5","6"]
print(words[1...]) // ["2", "3", "4", "5", "6"]
print(words[...3]) //["1", "2", "3", "4"]
print(words[..<2]) //["1", "2"]