Remove character accents in a String – Swift

Posted by

This is a re-work of an old post I did about 5 years ago (originally in Objective-C) but I thought I’d revisit this and re-post in Swift.

I was (not so recently) asked to capitalise some Greek strings in an app for a client, only problem I had was that the original string was provided to me in lowercase and had character accents.

Unbeknown to me at the time, uppercase words in Greek (and possibly other languages) loose the accents… 🤔

Not being Greek or having a greek keyboard layout I needed a way to tackle this.

The following code snippet successful strips out the character accents for Greek text allowing you then simply uppercase for your view.

// Original String
var originalString = "Γειά σου Κόσμε"

// Still has accents

// Uses folding
var formattedString = originalString.folding(options: .diacriticInsensitive,
                                             locale: Locale.current)

// Accents removed

As you can seen from the preceding code, we use the stringByFoldingWithOptions() with the option .diacriticInsensitive.

Available since iOS 2.0, stringByFoldingWithOptions() allows you too remove a range of character distinctions from a String().

Then .diacriticInsensitive option is just one of a few available to us when using stringByFoldingWithOptions() with our required string.

For more information – see documentation on Apple’s website

Whether this is a one time use or required for the majority of your app, something as simple as this would sit nicely in an Extension, ready to be called upon in your hour of need.

A Swift Playground with the above example is available here.


C.  🥃