swift
  1. swift-range-operators

Swift Range Operators

Swift provides three range operators as a way to represent a range of values. These range operators are useful in a variety of situations for working with collections, loops, and conditionals.

Syntax

Swift includes three range operators:

  • Closed Range Operator (…)
  • Half-Open Range Operator (..<)
  • One-Sided Range Operator (…)

Example

Here are some examples of Swift range operators:

// Closed Range Operator
for i in 1...5 {
    print(i)
}

// Half-Open Range Operator
let numbers = [1, 2, 3, 4, 5]
for i in 0..<numbers.count {
    print(numbers[i])
}

// One-Sided Range Operator
let names = ["John", "Jane", "James", "Jenny"]
print(names[2...])

Output

The output of the above code will be:

1
2
3
4
5

1
2
3
4
5

["James", "Jenny"]

Explanation

  • The closed range operator (…) includes both the start and end values of the range.
  • The half-open range operator (..<) includes the start value and excludes the end value of the range.
  • The one-sided range operator (…) includes all values from the start value to the end of the collection or array.

In the first example, the closed range operator is used for looping through the values 1 to 5 inclusive.

In the second example, the half-open range operator is used to loop through an array of numbers.

In the third example, the one-sided range operator is used to access a range of values from an array starting from a particular index.

Use

Swift range operators are useful for a variety of purposes, including:

  • Looping through a range of values
  • Accessing a range of values from an array or collection
  • Creating conditional statements based on a range of values

Important Points

  • Swift has three range operators: closed range (…), half-open range (..<), and one-sided range (…)
  • Closed range operator includes both start and end values of the range
  • Half-open range operator includes start value and excludes end value of the range
  • One-sided range operator includes all values from the start value to the end of the collection or array

Summary

Swift range operators provide a simple and powerful way to work with ranges of values. They are commonly used in loops and conditional statements, and can help make your code more concise and expressive. Whether you are a beginner or an experienced developer, understanding Swift range operators is an important part of mastering the Swift programming language.

Published on: