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

To find the first index of a substring in a string in Swift, you can use the range(of:) method provided by the String class. Here's an example:

main.swift
let myString = "Hello, world!"
let mySubstring = "world"

if let range = myString.range(of: mySubstring) {
    let startIndex = myString.distance(from: myString.startIndex, to: range.lowerBound)
    print("Found substring at index \(startIndex)")
} else {
    print("Substring not found")
}
291 chars
10 lines

In the above example, we first define the string that we want to search in (myString) and the substring that we want to find (mySubstring). We then use the range(of:) method to find the range of the substring within the string.

If the substring is found, range(of:) returns a Range<String.Index> object, which we can then use to calculate the index of the first character of the substring using distance(from:to:) method. If the substring is not found, range(of:) returns nil, and we print a message indicating that the substring was not found.

gistlibby LogSnag