UITextView Word Count in Swift

October 24th, 2017

Filed under: iOS Development | Be the first to comment!

Getting the word count of an iOS text view is a little more difficult than a Mac text view because the NSTextStorage class’s words property is not available on iOS. A starting point for getting the word count is to separate the components of the text view’s string by whitespace and newline characters.

let words = textView.text.components(separatedBy: .whitespacesAndNewlines)

The problem is the componentsSeparatedBy function treats empty strings as words. If you have an empty text view, the word count will be 1. Pressing the space bar increments the word count. If you hit the space bar 5 times, the word count goes up by 5 even though you didn’t type any words.

The solution to get an accurate word count is to filter the empty strings out of the array of words.

@IBOutlet weak var textView: UITextView!

let words = textView.text.components(separatedBy: .whitespacesAndNewlines)
let filteredWords = words.filter({ (word) -> Bool in
    word != ""
let wordCount = filteredWords.count

Leave a Reply

Your email address will not be published. Required fields are marked *