How to find synonyms with the Natural Language framework for iOS
Learn how to find similar words or sentences in Swift.
12 Jun 2023 · 3 min read
The possibility to find synonyms for a given word can help us improve the user experience in an iOS application, for example to provide more intelligent search results or being able to offer similar content.
The Natural Language framework provides the synonyms functionality out of the box with its NLEmbedding type which represents a vector map of strings.

We can use its neighbors function to find synonyms as follows:
func synonyms(for word: String, maximumCount: Int = 5) -> [String] {guard let embedding = NLEmbedding.wordEmbedding(for: .english) else { return [] }let synonyms = embedding.neighbors(for: word, maximumCount: maximumCount).map { $0.0 }return synonyms}
To support different languages, we could improve the method above by detecting the language automatically. The Natural Language framework supports this functionality out of the box. Check out this article on how to detect the language of a text with the Natural Language framework to learn how to do that.
The neighbors function not only provides synonyms but also their distance to the given word. Strings that are semantically similar have a smaller distance value. We can find out the distance between two words directly as follows:
let distance = embedding.distance(between: word, and: anotherWord)
The distance functionality can also be used to find out similarity between sentences, which can be really usefull for example when building an FAQ service, it could suggest related questions based on the user's entered question.
To get the distance between two sentences, we create an embedder by using its sentenceEmbedding function and then use it just like we used it with words:
guard let embedding = NLEmbedding.sentenceEmbedding(for: .english) else { return }let distance = embedding.distance(between: sentence, and: anotherSentence)

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips