How to create a custom NSCharacterSet?

ixany picture ixany · Sep 11, 2015 · Viewed 14k times · Source

I’m using CharacterSet.urlQueryAllowed to add percent-encoding to a String.

Some characters are not encoded the way I expected (i.e. & and ? are not changed). That being said, I had the idea to build a custom CharacterSet, ideally based on an existing one.

What’s the best approach to do so?

Answer

Sulthan picture Sulthan · Sep 11, 2015

The most typical way to create a new character set is using CharacterSet(charactersIn:), giving a String with all the characters of the set.

Adding some characters to an existing set can be achieved using:

let characterSet = NSMutableCharacterSet() //create an empty mutable set
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLQueryAllowedCharacterSet())
characterSet.addCharactersInString("?&")

or in Swift 3+ simply:

var characterSet = CharacterSet.urlQueryAllowed
characterSet.insert(charactersIn: "?&")

For URL encoding, also note Objective-C and Swift URL encoding