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.swift291 chars10 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