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.
We introduce the countWords
function. This function receives a String
and returns an Int
—the count of words in the string.
for
-loop returns each value as a Character type.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
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.