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 stringlet name = "Theodore"// get some indexlet index1 = name.index(before:name.endIndex)let index2 = name.index(before:index1)// access the index in the stringprint(name[index1]) // eprint(name[index2]) // r
Explanation
- Line 2: We create a string.
- Line 5: We provide the value of the
endindexfunction, the position one greater than the last valid subscript argument, as an argument to theindex(before:)function. We save the return value inindex1. - Line 6: We provide
index1function as an argument to theindex(before:)function and saved the return value inindex2. - Lines 9 to 10: We use the indexes. We access the characters of the string we created and print the values to the console.