CharacterSet’s and How to Use Them in Swift?

What Is a CharacterSet?

Yunus Koçyiğit
1 min readAug 19, 2019

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.

How To Know What’s Inside a CharacterSet?

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.

CharacterSet+getCharacters()

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.

Why And How To Use a CharacterSet?

  • 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.

Extending CharacterSet

We can extend CharacterSet struct to add our own CharacterSets.

Custom CharacterSet Example

--

--