Analyzing Sentiment in Text

First, import the Natural Language framework and create an NLTagger instance using the .sentimentScore tag scheme.

.sentimentScore returns a score from -1.0 to 1.0 for a given text. The closer the score is to 1.0, the more positive the sentiment; the closer it is to -1.0, the more negative; 0.0 indicates neutral.

import Foundation
import Playgrounds
import NaturalLanguage

#Playground {
    let tagger = NLTagger(tagSchemes: [.sentimentScore])
}

tagger-result

After creating the NLTagger, assign the string to analyze to tagger.string, then call enumerateTags to enumerate sentiment tags within the specified range.

  • in specifies the range to analyze; the example passes the entire text.
  • unit specifies the granularity of analysis; the example uses .paragraph, scoring by paragraph.
  • scheme specifies the tag scheme; here it is .sentimentScore.
  • options configures enumeration options; an empty array means no extra options are enabled.
import Foundation
import NaturalLanguage
import Playgrounds

#Playground {
    let tagger = NLTagger(tagSchemes: [.sentimentScore])
    let text = "This movie is really great!"

    tagger.string = text
    tagger.enumerateTags(
        in: text.startIndex..<text.endIndex,
        unit: .paragraph,
        scheme: .sentimentScore,
        options: []
    ) { sentimentTag, _ in
        if let sentimentString = sentimentTag?.rawValue,
            let score = Double(sentimentString)
        {
            print(score)
            return true
        }

        return false
    }
}

The callback receives an optional NLTag whose rawValue is a string. The example converts it to a Double and prints the result; returning true continues enumeration, while returning false stops it.

This score indicates the sentiment tendency, not a probability or confidence. To further classify text as positive, neutral, or negative, you need to set thresholds based on real-world data.

tagger-result-2