user2924482 user2924482 - 5 months ago 14
Swift Question

Swift: Compare the first character of string

How can I compare the first character of a String against a character in Swift? For example:

Pseudo code:

str = "my name is John"

if str[0] == m {
}

Answer
let s = "abcd"

if s.hasPrefix("a") {  // takes a String or a literal
}

if s.characters.first == "a" {  // takes a Character or a literal
}