Grant Emerson

Editing Strings with CharacterSet

Editing Strings with CharacterSet — SwiftMoji Entry #17

The Foundation framework provides many great utilities to build upon the Swift Standard Library. One of these utilities is the CharacterSet struct (or the NSCharacterSet class in Objective-C) which is designed to hold a set of Unicode characters. A CharacterSet can be passed in as an argument to many of Foundation’s built-in extensions to String. For example, CharacterSet’s static member called symbols could be used to remove all emojis from a String. The symbol CharacterSet can simply be passed into the components(seperatedBy:) method on the String to be formatted. The resulting Array can then be converted back into a String using the joined() method. CharacterSet includes a variety of static instances such as alphanumerics or punctuationCharacters that come in handy when performing complex searches or parsing data.

import Foundation

let emojis = CharacterSet.symbols

var 🗺 = "Forwards 50 ft. 👆 Left 20 ft. 👈 Backwards 10 ft. 👇"
print(🗺) // Forwards 50 ft. 👆 Left 20 ft. 👈 Backwards 10 ft. 👇
🗺 = 🗺.components(separatedBy: emojis).joined()
print(🗺) // Forwards 50 ft.  Left 20 ft.  Backwards 10 ft.
Tagged with: