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.swift180 chars8 lines
This code will output:
main.swift30 chars2 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