Skip to content

NSSpellChecker

Ken Harris edited this page Feb 5, 2018 · 3 revisions

You might be tempted to count words using:

NSSpellChecker.shared().countWords(in: text, language: nil)

First, be aware that unlike most methods that return nil on error (or return an Error, or @throw an exception) this returns -1. This method even returns -1 when passed "", for example.

Second, it's not very fast. It seems to connect to the shared (XPC) spelling service, which adds an order-of-magnitude slowdown. Instead, I recommend:

text.enumerateSubstrings(in: text.startIndex..<text.endIndex,
                         options: [.byWords, .localized]) { (_, _, _, _) in
    self.words += 1
}

Yes, it still works for languages like Japanese which don't use whitespace to separate words.

I have no idea what benefit it would have to contact the XPC service for this. Instruments shows that it's spending most of its time in _findMisspelledWordsInString, which I really don't need here.

It's still not anywhere near as fast as wc (<4.0sec vs <0.04sec, for seq 100000), but it's probably fast enough for you, and it's still doing a lot more work (man wc: "A word is defined as a string of characters delimited by white space characters").

Clone this wiki locally