To find the first character in a string in Swift, you can use the first
property of the String
type. Here's an example:
main.swift94 chars5 lines
Alternatively, you can use the prefix
method to get a substring containing only the first character of the string, and then use the first
property of that substring:
main.swift104 chars5 lines
Both of these approaches use optional binding with the if let
syntax to safely unwrap the optional first character. If the string is empty, the optional binding will fail and the code inside the if
block won't be executed.
gistlibby LogSnag