What is index(before:) method in Swift?

Overview

index(before:) is a string instance method that returns the position immediately before the given index. The before here refers to the index of the character immediately before the given index.

Syntax

str.index(before:i)

Parameters

i: A valid index of the collection. It must be greater than the startIndex property.

Return value

This method returns the index value immediately before i.

Example

Let’s look at the code below:

// create a string
let name = "Theodore"
// get some index
let index1 = name.index(before:name.endIndex)
let index2 = name.index(before:index1)
// access the index in the string
print(name[index1]) // e
print(name[index2]) // r

Explanation

  • Line 2: We create a string.
  • Line 5: We provide the value of the endindex function, the position one greater than the last valid subscript argument, as an argument to the index(before:) function. We save the return value in index1.
  • Line 6: We provide index1 function as an argument to the index(before:) function and saved the return value in index2.
  • Lines 9 to 10: We use the indexes. We access the characters of the string we created and print the values to the console.

Free Resources