Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
communitycreator

How to create a range in Swift

Theodore Kelechukwu Onyejiaku

Overview

A range is an interval of number values that has a starting point of, but does not include, the upper point. For example, the range of 1–5 is 1, 2, 3, 4. We can create a Range instance in Swift using the half-open range operator (..<).

Syntax

variable = lowerbound ..< upperbound

Parameters

  • lowerbound: This is the lowest range value.
  • upperbound: This is the limit of the range but is not included as part of the range.

Return value

A range is returned.

Code example

// create some ranges
let range1 = 0 ..< 5
let range2 = 0 ..< 0  // empty range

// print values in the range
for value in range1 {
  print(value)
}

// print values in empty range
for value in range2 {
  print(value)   // nothing is printed
}
Create a range in Swift

Explanation

  • Line 2–3: We created some ranges using the half-open range operator (..<). One of them is empty and the other is not.
  • Line 6–11: We used the for-in loop to loop through the ranges and printed to the console.

RELATED TAGS

swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring