Building an NSCharacter set to restrict a UITextField for entering user names. I want the user to be able to also enter an underscore (so [A-Za-z0-9_]) but alphanumericCharacter
Another way would have been to make it mutable and add it.
Objective-C
NSMutableCharacterSet *characterSet = [NSMutableCharacterSet alphanumericCharacterSet];
[characterSet addCharactersInString:@"_"];
Swift
let characterSet = NSMutableCharacterSet.alphanumeric()
characterSet.addCharacters(in: "_")
You could verify it has been added (in a Playground) with:
characterSet.characterIsMember(UInt16(Character("^").unicodeScalars.first!.value)) // false
characterSet.characterIsMember(UInt16(Character("_").unicodeScalars.first!.value)) // true -- YAY!
characterSet.characterIsMember(UInt16(Character("`").unicodeScalars.first!.value)) // false