How do you use String.substringWithRange? (or, how do Ranges work in Swift?)


You can specify the range operator using two syntaxes (..< or ...). These two syntaxes are used for different purposes. As part of the first syntax, the starting and ending values of the range are included. In contrast, the second syntax includes a starting value as well as an optional ending value.

For example, you want to specify a range from the number 1 to 4. You can define it like this 1..<5 syntax of the range operator. In a similar way, to specify the range from 1 to 5, you can create a range like the 1...5 syntax of the range operator. The two syntaxes can both be used with a for-in loop for iterating.

Which types of range operators are there in Swift?

There are two types of range operators in Swift −

  • The closed range operator (...) − This operator defines a range that includes both the first and last values. For example, 1...5 defines a range of integers from 1 to 5, inclusive.

  • The half-open range operator (..<) − This operator defines a range that includes the first value but excludes the last value. For example, 1..<5 defines a range of integers from 1 to 4.

It is possible to use both operators with integers, floating-point numbers, and strings if they conform to the Comparable protocol.

Example

let closedRange = 1...5
let halfOpenRange = 1..<5
let strClosedRange = "a"..."e"
let strHalfOpenRange = "a"..<"e"

Both types of ranges can also be used in various ways such as in for loops, to access elements in an array, to check if a value is within a specific range, and so on.

How do ranges work in Swift?

In Swift, ranges are defined using the range operator (..< or ...) and specify a range of values. The range operator ..< defines a range that includes the first value, but excludes the last value, while the range operator ... includes both the first and last values.

For example, 1..<5 defines a range of integers from 1 to 4, and 1...5 defines a range of integers from 1 to 5.

Ranges can be used in various ways in Swift

In for loops

Range operators are very commonly used with the for loop. Range operators provide flexibility in for loop to iterate elements.

Example

import Foundation
for element in 1...5 {
   print("Element: \(element)")
}

Output

Element: 1
Element: 2
Element: 3
Element: 4
Element: 5

To access elements in an array

Range operators can be used to access the group of elements from an array or other collection.

Example

import Foundation
let languages: [String] = ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
let subarray = languages[1..<3]
print("Original array: \(languages)")
print("Subarray: \(subarray)")

Output

Original array: ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
Subarray: ["Java", "Swift"]

Using a range to iterate over an array

This is the most common use of the range operator to iterate an array in an easy way.

Example

import Foundation
let languages: [String] = ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
for index in 0..<languages.count {
   print("Element: \(languages[index])")
}

Output

Element: PHP
Element: Java
Element: Swift
Element: Python
Element: JavaScript
Element: GoLang

Using a range to check if a value is within a specific range

You can check if a value exists in a range or not. The range operator makes this easy to check.

Example

import Foundation
let number = 25
if (10..<30).contains(number) {
   print("\(number) is within the range of 10 to 30")
}

Output

25 is within the range of 10 to 30

Using a range to check if a value is in a range of a switch case

A switch statement is very powerful in Swift language. You can use the range operator in Switch’s cases.

Example

import Foundation
let score = 85
switch score {
case 0..<50:
   print("You failed")
case 50..<70:
   print("You passed")
case 70...100:
   print("You got an A")
default:
   print("Invalid score")
}

Output

You got an A

Using a range with the stride(from:to:by:) function

You can provide a range in stride() function to provide the starting and ending value along with an increment count.

Example

import Foundation
for i in stride(from: 0, to: 10, by: 2) {
   print(i)
}

Output

0
2
4
6
8

How to use String.substringWithRange?

In Swift 5 we no longer have access to substring() methods for they are deprecated. We will discuss all alternatives and understand them in detail.

The substring(with:) method has been updated to String[startIndex..<endIndex] or String[startIndex...] or String[..<endIndex] in Swift 4.2 and above to extract a substring from a string using a range. Here's an example using this new syntax −

Example

import Foundation
let sampleString = "Hello World!"
let index = sampleString.index(sampleString.startIndex, offsetBy: 5)
let substring = sampleString[..<index]
print("Original string: \(sampleString)")
print("Substring: \(substring)")

Output

Original string: Hello World!
Substring: Hello

Conclusion

In swift, ranges are used for creating a range of values, and it can be various applications. The closed range operator and the half-open range operator are the two different types of range operators. Ranges can be used in switch statements, for loops, stride(from:to:by:) functions, accessing elements in arrays, determining whether a value falls inside a given range and many other situations.

Updated on: 28-Feb-2023

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements