How to count the occurrences of each word in a string with Swift

1 Answer

0 votes
import Foundation

func countWordOccurrences(in str: String) -> [String: Int] {
    // Split the text into words
    let words = str.lowercased().components(separatedBy: CharacterSet.alphanumerics.inverted).filter { !$0.isEmpty }
    
    // Create a dictionary to hold word counts
    var wordCount: [String: Int] = [:]
    
    // Count occurrences of each word
    for word in words {
        wordCount[word, default: 0] += 1
    }
    
    return wordCount
}

let str = "Swift is a high-level general-purpose, multi-paradigm, " + 
          "compiled programming language created by Chris Lattner " + 
          "in 2010 for Apple Inc. Swift maintained by the open-source community."

let wordOccurrences = countWordOccurrences(in: str)

print(wordOccurrences)



/*
run:
     
["purpose": 1, "a": 1, "multi": 1, "is": 1, "high": 1, "lattner": 1, "community": 1, "the": 1, "swift": 2, "inc": 1, "for": 1, "level": 1, "paradigm": 1, "by": 2, "language": 1, "source": 1, "maintained": 1, "programming": 1, "apple": 1, "compiled": 1, "in": 1, "2010": 1, "created": 1, "general": 1, "open": 1, "chris": 1]
     
*/
 

 



answered Mar 2, 2025 by avibootz
...