Swift version: 5.2
Sentiment analysis uses machine learning to tell us whether a piece of text is considered positive or negative, and it’s baked right in to iOS with the NaturalLanguage framework.
To perform sentiment analysis takes a handful of lines of code: we create an
NLTagger that creates a sentiment score, assign some text for the tagger to analyze, read the sentiment value, then convert it to a
Double so it can be used.
Let’s look at the code first, then I’ll break down what it means:
// set up our input let input = "Hacking with Swift is awesome" // feed it into the NaturalLanguage framework let tagger = NLTagger(tagSchemes: [.sentimentScore]) tagger.string = input // ask for the results let (sentiment, _) = tagger.tag(at: input.startIndex, unit: .paragraph, scheme: .sentimentScore) // read the sentiment back and print it let score = Double(sentiment?.rawValue ?? "0") ?? 0 print(score)
Now let’s break that down, starting with the
tagger.tag() call that has three options and two return values.
The options are:
What we get back is the sentiment score as an
NLTag, plus the range where it was found. We don’t care about the range, so we’ll ignore it.
The other value, that
sentiment constant, is an
NLTag? with a raw value of a
String. If everything went to plan that string will contain a
Double in the range of -1 (very negative) to +1 (very positive), so to read that value we need to do some careful typecasting:
let score = Double(sentiment?.rawValue ?? "0") ?? 0 print(score)
That means “attempt to read the sentiment’s raw value, but use the string ‘0’ if that fails, then attempt to convert that to a
Double, but use the value 0 if that fails.”
The end result will be a
score value that is somewhere between -1.0 (very negative) and 1.0 (very positive), or 0.0 if the text is neutral or nothing could be read.
Note: In this example I’ve used a short piece of text, but obviously the framework works best with lots of text – it’s hard to come to a conclusion given only a few words, and you’ll often get inaccurate readings doing so.
SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!
Available from iOS 13.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.