Swift - How to check a string not included punctuations and numbers

Viewed 214

I want to check a string to be able to understand that string is suitable for using as a display name in the app. Below block looks only for english characters. How can I cover all language letters? Also all punctuations and numbers won't be allowed.

func isSuitableForDisplayName(inputString: String) -> Bool {

    let mergedString = inputString.stringByRemovingWhitespaces

    let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    if mergedString.rangeOfCharacter(from: characterset.inverted) != nil {
       return false
    } else {
       return true
    }
}
1 Answers

You can use CharacterSet.letters, which contains all the characters in the Unicode categories L and M.

Category M includes combining marks. If you don't want those, use:

CharacterSet.letters.subtracting(.nonBaseCharacters)

Also, your way of checking whether a string contains only the characters in a character set is quite weird. I would do something like this:

return mergedString.trimmingCharacters(in: CharacterSet.letters) == ""
Related