Reputation: 95
I want to determine what the first letter is in a text field. I want to determine whether the first letter is @ or #. What should I do?
func search() {
searchBar.searchTextField.text?.first
}
Upvotes: 0
Views: 984
Reputation: 3867
To make an optional string capable of checking for a prefix from a number of strings:
extension Optional where Wrapped: StringProtocol {
func hasPrefix(_ ss: [String]) -> Bool {
guard let s = self else { return false }
return ss.first(where: s.hasPrefix) != nil
}
}
searchBar.searchTextField.text.hasPrefix(["@", "#"])
Upvotes: 1
Reputation: 2217
You can declare a variable with the characters you are checking for, and check if the first character of your UITextField
is in that array:
let checkedCharacters = ["@", "#"]
if let firstCharacter = searchBar.searchTextField.text?.first {
let containsCharacter = checkedCharacters.contains(firstCharacter)
}
Upvotes: 1