CharacterSet’s and How to Use Them in Swift?

a CharacterSet is a struct defined in Foundation Framework. It represents certain character arrays like;

  • decimal digits (CharacterSet.decimalDigits)
  • white space characters (CharactersSet.whitespaces),
  • lowercase letters (CharacterSet.lowercaseLetters)
  • illegal characters (CharacterSet.illegalCharacters)
  • punctuation characters (CharacterSet.punctuationCharacters)
  • and many more.

Unfortunately, the CharacterSet struct doesn’t have a method or property to get characters by default, but fortunately, we can extend ChracterSet struct to get characters from it.


Let’s look at what’s inside a sample CharacterSet.

Characters inside of .decimalDigits CharacterSet

As you can see, CharacterSet.decimalDigits CharacterSet includes decimal digit characters from many different languages, also in emoji form.

You can look at the documentation for the list of predefined CharacterSets.

  • Trimming unwanted characters from a String (removing from start and end)
  • Filtering unwanted characters from a String (removing from anywhere in String)
  • Validating a String
  • Representing certain characters to allow in a String (like percentEncoding)
Code Sample for CharacterSet+String

As on the Swift code example, we can extend String struct to add CharacterSet helpers.

We can extend CharacterSet struct to add our own CharacterSets.

Custom CharacterSet Example