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.
str.index(before:i)
i: A valid index of the collection. It must be greater than the startIndex property.
This method returns the index value immediately before i.
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
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.index1 function as an argument to the index(before:) function and saved the return value in index2.