Consecutive spaces and newlines are not combined into one common space of spaces, so you just get a bunch of empty βwordsβ between consecutive whitespace characters. Get rid of this by filtering out empty lines:
let components = str.components(separatedBy: .whitespacesAndNewlines) let words = components.filter { !$0.isEmpty } print(words.count) // 17
The above text will print 17 because you did not include , as a split character, so the line "planners,are" treated as one word.
You can also break this line by adding punctuation to a set of delimiters, for example:
let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters) let components = str.components(separatedBy: chararacterSet) let words = components.filter { !$0.isEmpty } print(words.count) // 18
You will now see counter 18 as you expect.
source share