OneBite.Dev - Coding blog in a bite size

Convert A String To Uppercase In Swift

Code snippet for how to Convert A String To Uppercase In Swift with sample and detail explanation

Managing the casing of text is a commonly done operation in any kind of software development. In Swift, converting a string to uppercase is pretty straightforward. Lets dive into how this operation can be done.

Code snippet: Converting a string to uppercase in Swift

Let’s consider that you have a string that needs to be converted into uppercase. Below is a simple code snippet that does just that in Swift:

let originalString = "hello, world"
let uppercasedString = originalString.uppercased()
print(uppercasedString)  // Outputs: "HELLO, WORLD"

Code Explanation: Converting a string to uppercase in Swift

This example program starts by creating a string named originalString. This is the string that we want to convert to uppercase.

  1. let originalString = "hello, world": This line of the script declares a constant named originalString and initializes it with the string “hello, world”.

  2. let uppercasedString = originalString.uppercased() : Here, we are declaring a new constant named uppercasedString to hold the result of converting originalString into uppercase. Swift’s string type has a method called uppercased(). It is invoked by calling it on an instance of a string to be converted and it returns a new string which is an uppercase version of the input string.

  3. print(uppercasedString): In this line, we are printing out the newly created uppercase string. The result is “HELLO, WORLD” printed on the console.

In short, Swift makes it incredibly easy to convert a string to uppercase using its built-in uppercased() method. It doesn’t modify the original string but instead produces a brand new one in uppercase. Remember, because Swift’s strings are value types (not reference types), the original string is not modified when we create a new uppercase string from it.

swift