Ad space (banner)
๐ŸฆSwift Lessons
Lesson 64 / 68

Checking Whether Two Words Are Anagrams

In this lesson you will learn how to check whether two words are anagrams in Swift, covering how to sort and compare strings. This is for anyone searching for "Swift anagram check implementation".

An anagram is a different word made from the same letters rearranged (for example, listen and silent). Sort the letters of both strings and see whether they match.

The sample code lower-cases each string and sorts it as an array of characters with a.lowercased().sorted(), doing the same to the other before comparing. "listen" and "silent" are made of the same letters, so they match once sorted.

A common stumbling block for beginners is not allowing for case differences. The sample folds to lower case with lowercased() before comparing; skip that and the same word in different cases is judged to be different.

It is a basic technique for comparing strings while ignoring order, and for long strings, counting how often each character occurs is faster.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)