Converting a string to lower case

Swift:
Converting a string to lower case

How to:

Swift makes this easy with a property called lowercased. Here’s how you use it:

let originalString = "Hello, World!"
let lowercasedString = originalString.lowercased()
print(lowercasedString) // "hello, world!"

Sample output:

hello, world!

Deep Dive:

Historically, ensuring consistent string case has been crucial in programming, mainly since early computers were very case-sensitive. In Swift, lowercased() is a method available on instances of the String type. By invoking it, you convert all characters within the string that have lowercased variants to their lowercased forms.

Alternatives to lowercased() could be manually traversing the string and replacing each character with its lowercased equivalent by using a mapping function. But, honestly, that’s reinventing the wheel.

String lowercasing has some nuances. For instance, the lowercased() method uses the current locale to handle specific language casing rules, which is not always the desired behavior. If you need to perform locale-independent conversions, you can resort to lowercased(with: Locale?) and pass nil as the Locale:

let turkishString = "İstanbul"
let lowercasedTurkishString = turkishString.lowercased(with: nil)
print(lowercasedTurkishString) // "i̇stanbul", correct in Unicode, but 'I' without dot might be expected in Turkey.

The implementation of lowercased() under the hood leverages the Unicode standard which includes complex mapping rules for characters in various scripts, not all of which are a simple matter of ‘a’ replacing ‘A’.

See Also:

To explore more on strings and character transformations in Swift, dip into the following resources: