Member-only story
Enumerating and Counting Text Components in Swift
No need to reinvent the wheel when what we need is just there!
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: