find the first character in a string in swift

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.swift
let str = "Hello, World!"
if let firstChar = str.first {
    print(firstChar) // prints "H"
}
94 chars
5 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.swift
let str = "Hello, World!"
if let firstChar = str.prefix(1).first {
    print(firstChar) // prints "H"
}
104 chars
5 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