HomeSearch

Swift Range Examples (index, offsetBy)

Use ranges with startIndex and endIndex. Call the index func and specify offsetBy.
Range. The numbers 0, 1 and 2 are sequential—this is a range. In Swift we can create a range with special syntax. We can even loop over a range.
Bounds. With startIndex and endIndex, we can test the bounds of a range. Count returns the number of elements. And index() with offsetBy changes the start or end.
Loop example. Here we create a constant range of the values 0, 1 and 2. With this syntax, the 0 and the 2 are both included. We use a for-in loop over the range.

Here: The term "range" is just an identifier for the range of values. This syntax includes 0 and 2.

Let: A range can be specified directly in the loop expression (after in). In this usually a clearer way to write a loop.

Swift program that uses range syntax // Create a range. let range = 0...2 // Use a for-in loop over the range. for value in range { print(value) } Output 0 1 2
StartIndex, endIndex. This example shows the startIndex and endIndex properties. These return the first and last indexes in the range.

Note: There is some complexity here. EndIndex here is one greater than the last included value.

Count: With count, we get an Int that is equal to the number of values within the range. Here that is 6.

Int
Swift program that uses startIndex, endIndex, count let range = 5...10 // A range has a startIndex and an endIndex. // ... The endIndex is one more than the last included index. print(range.startIndex) print(range.endIndex) // Count returns the number of elements in the range. print(range.count) Output ClosedRangeIndex<Int>(_value: Swift._ClosedRangeIndexRepresentation<Swift.Int>.inRange(5)) ClosedRangeIndex<Int>(_value: Swift._ClosedRangeIndexRepresentation<Swift.Int>.pastEnd) 6
Half-open ranges. In Swift we can create ranges that do not include the second (end) number. These use a "less than" sign. These are called half-open ranges.

Tip: With this operator, we can get a range of all the indexes in an array without subtracting one from the array's count.

Quote: [A range] is said to be half-open because it contains its first value, but not its final value (Swift Programming Language).

Swift program that uses half-open range operator // This range does not include the last number. let values = 0..<5 // Loop over values in the exclusive-end range. for value in values { print(value) } Output 0 1 2 3 4
Negative numbers. Usually ranges have positive starts and ends. But we can have negative numbers in our ranges. The start (even if negative) must be less than the end.

Note: The range here is specified directly within the for-in loop. This makes for simpler code.

Swift program that uses negative number in range // A range can start at a negative number. for id in -4...2 { print(id) } Output -4 -3 -2 -1 0 1 2
Index, offsetBy. Sometimes we want to create a range based on an existing one. We can use index (with offsetBy) on the startIndex or endIndex. Here we increment the range's start by 2.

Tip: With index() we can reduce an index by passing a negative Int as the second argument.

Note: When we print a range, we see information about the range, not just a start and end integer pair.

Swift program that advances range var range = 0...3 // Create a new range based on an existing range. // ... Advance the startIndex by 2. var x = range.index(range.startIndex, offsetBy: 2)..<range.endIndex // Display ranges. print(range) print(x) Output 0...3 ClosedRangeIndex<Int>(_value: Swift._ClosedRangeIndexRepresentation<Swift.Int>.inRange( 2))..<ClosedRangeIndex<Int>(_value: Swift._ClosedRangeIndexRepresentation<Swift.Int>.pastEnd)
Invalid range. A range's start must be less than or equal to its end. It cannot be larger. Here we encounter the "can't form Range" error in a compiled Swift program.
Swift program that has invalid range // This will cause an error. var range = 100...0 // Not reached. print(range) Output fatal error: Can't form Range with end < start (lldb)
Range of array indexes. A half-open range can return all valid indexes for an array. The end is one less than the count. Here we use for-in on all array indexes.Array
Swift program that uses range of indexes, array // This string array has three elements. let animals: [String] = ["bird", "cat", "fox"] // Loop through all indexes in the array. for index in 0..<animals.count { print(index) print(animals[index]) } Output 0 bird 1 cat 2 fox
Substring note. Ranges are useful when taking substrings. The index() offsetBy method helps us index into a string. And then we can access the string by a range.Substring
A history lesson. Range syntax has been changed in Swift 2 and Swift 3. This is confusing. But in many ways the newer syntax forms are clearer and easier to use.
Ranges are used with arrays and strings. They can create a sequence for a for-in loop. Closed ranges, and half-open ones, are common in Swift programs.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls