Enumerating and Counting Text Components in Swift

No need to reinvent the wheel when what we need is just there!

Gabriel Theodoropoulos

--

Photo by Pixabay from Pexels

It’s sometimes necessary either to enumerate, or to just count various components of a text in our apps. Examples of that would be to find the total number of characters, words, paragraphs, lines, and more in the entire or part of the text. Quite probably the first thought towards achieving that would be to go by doing some custom work; to break the original string into pieces based on the space character, new line character, and so on, to count the resulting parts and eventually act on them. However, we really do not have to reinvent the wheel, as Swift provides us with the tools to do all that.

As you’ll see in the next parts of this post, it’s quite trivial to get words, paragraphs and other text components from a string; it’s all there in the Foundation framework. But it’s the kind of APIs that nobody really cares about until they come to need such functionalities in their apps.

The basics

Starting with the fundamentals in an Xcode playground, let’s make the following “lorem ipsum” the sample text to work on in this post:

The first thing to focus on for the sake of completeness is how we can get the total number of characters in the above text. That’s easy, it does not require any specific API to manage it, and most likely you know how to do it already by accessing the count property of text:

The above will give us the length of the text string anywhere we're going to use it. If we'd rather having something simpler than this statement, we could return it from a read-only computed property like so:

--

--

Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev