How to compare strings based on the number of vowels it has in Swift?

Photo by Maxwell Nelson on Unsplash

As expected, Swift String conforms to Comparable protocol, so it implements all the generic operators for comparison, like β€˜<’, β€˜>’, β€˜!=’, etc… So, it has default comparison rules, which could be used to compare or sort strings.

But what if we want to change this default comparison rule, and use our own rule. The answer to it will be overwrite the existing operators.

Here is an example, we customize rule to use the number of vowels in string, whoever has fewer vowels will be smaller.

The last two lines of testing code will have:

  • false
  • true

as results.

--

--