How do ranges (closed, half-open) work in Swift?

Ranges in Swift are powerful tools for defining sequences of numbers or characters. They come in several forms: closed ranges, half-open ranges, and one-sided ranges.

Closed Ranges

A closed range includes both its lower and upper bounds. It is defined using the `...` operator.

let closedRange = 1...5 // This represents the numbers 1, 2, 3, 4, and 5

Half-Open Ranges

A half-open range includes the lower bound but excludes the upper bound, defined using the `..<` operator.

let halfOpenRange = 1..<5 // This represents the numbers 1, 2, 3, and 4

One-Sided Ranges

One-sided ranges allow you to define a range without specifying one of its bounds.

let oneSidedLowerBound = 1... let oneSidedUpperBound = ...5 // Lower bound includes 1 to any upper value and upper bound includes any lower value to 5

Swift Ranges Closed Ranges Half-Open Ranges One-Sided Ranges