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

To find the first index of a specific character in a Swift string, you can use the firstIndex(of:) method provided by the Swift Standard Library. This method returns the index of the first occurrence of the specified character in the string, or nil if the character is not found.

Here's an example:

main.swift
let text = "Hello, world!"

if let index = text.firstIndex(of: ",") {
    print("The first comma is at index \(index)")
} else {
    print("The string does not contain a comma")
}
180 chars
8 lines

This code will output:

main.swift
The first comma is at index 5
30 chars
2 lines

In this example, we first define a string text. We then call the firstIndex(of:) method on the string, passing in the character , as the argument. This method returns an optional Index value, so we use optional binding to check if the value is nil or not. If the value is not nil, we print the index of the first comma. If the value is nil, we print a message indicating that the string does not contain a comma.

gistlibby LogSnag