OneBite.Dev - Coding blog in a bite size

Capitalize A String In Swift

Code snippet for how to Capitalize A String In Swift with sample and detail explanation

Swift provides seamless options to manipulate strings including capitalizing. This article focuses on how one can capitalize a string in Swift via a simple practical code snippet and its subsequent explanation.

Code snippet to Capitalize a String in Swift

Here’s a simple code snippet that demonstrates how to capitalize a string in Swift:

let str = "this is to be capitalized."
let capitalizedStr = str.capitalized
print(capitalizedStr)

When you run this code, it will output: "This Is To Be Capitalized."

Code Explanation for Capitalizing a String in Swift

This tutorial uses Swift’s built-in capitalized property of the String type to perform the string capitalization:

  • The first line of the code let str = "this is to be capitalized." declares a constant (immutable variable) str and sets it equal to the string “this is to be capitalized”.

  • On the second line, another constant capitalizedStr is declared. This is set equal to str.capitalized. The capitalized property of a string in Swift capitalizes the first character of each word in the string. Therefore, the str.capitalized would result in “This Is To Be Capitalized.”

  • The third line of code print(capitalizedStr) prints the capitalized string to the console.

So, that’s it! That’s how you capitalize a string in Swift. Despite its simplicity, string capitalization has various crucial applications like enhancing the visual presentation of data to the users.

swift