find the last index of a substring in a string in swift

You can use the lastIndex(of:) method to find the last index of a substring in a string in Swift. Here's an example:

main.swift
let str = "hello world"
let substr = "world"

if let index = str.lastIndex(of: substr) {
    print("Last index of '\(substr)' in '\(str)' is: \(index)")
} else {
    print("Substring '\(substr)' not found in '\(str)'")
}
221 chars
9 lines

This code will output:

main.swift
Last index of 'world' in 'hello world' is: 6
45 chars
2 lines

Note that lastIndex(of:) returns an optional String.Index because the substring might not be present in the string. You can use optional binding or a guard statement to check if the index is not nil before using it.

gistlibby LogSnag