What is the index(after:) method in Swift?

Overview

The index(after:) method in Swift returns the position immediately after the given index. The after in this method refers to the index of the character that comes directly after the given index.

Syntax

str.index(after:i)

Parameters

i: This is a valid index of the collection. It must be less than the endIndex property.

Return value

This method returns the index value that comes immediately after i.

Code example

// create some strings
let name = "Theodore"
let language = "Swift"
// get some index
let index1 = name.index(after:name.startIndex)
let index2 = language.index(after:language.startIndex)
// access the index in the string
print(name[index1])
print(language[index2])

Code explanation

  • Lines 2–3: We create two strings, name and language.
  • Lines 6–7: We get the index of some characters in the strings, using the index(after:) method.
  • Lines 10–11: Using the index we got, we access the characters of that index in the strings we created earlier. Then, we print the values to the console.

Free Resources