Home
Swift
Word Count Function
Updated Sep 2, 2023
Dot Net Perls
Word count. Sometimes a document may have a certain file size, but the word count is clearer for estimating its length. A function that counts words in Swift can be developed.
With a for-loop over the characters, we can test each character with Character type properties. Some logic is required to test for whitespace.
for
Example. We introduce the countWords function. This function receives a String and returns an Int—the count of words in the string.
Step 1 We loop over the characters in the string. The for-loop returns each value as a Character type.
String
Step 2 We test the previous character to see if it is whitespace that could start a word. We also test the current character for a letter.
Step 3 Because we have to test two characters at once on each iteration, we need to set the previous character here.
Step 4 We return the total number of words in the string, based on the result of the iterative function.
func countWords(source: String) -> Int { var count = 0 var previous: Character = " " // Step 1: loop over string characters. for c in source { // Step 2: test previous character for whitespace, and current for letter, number or punctuation. if previous.isWhitespace { if c.isLetter || c.isNumber || c.isPunctuation { count += 1 } } // Step 3: set previous. previous = c } // Step 4: return count of words. return count } // Use word counting function. let input = "Cat, bird and dog." let result = countWords(source: input) print(result)
4
Summary. It is possible to develop an iterative word count algorithm in Swift, and this gives accurate results for English. It is also fast, as no regular expressions are used.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 2, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen