How to capitalize first letter in Swift

Jan 28, 2024#swift#strings

Capitalizing the first letter of a string is often done for aesthetic or formatting reasons. The difference between capitalizing the first letter of each word, capitalizing the first letter of a sentence, and using all caps (uppercase) lies in the specific style and purpose of text presentation.

  • Title case: Capitalize first letter of each word, often used for titles, headings, or any text where each word is considered important.
  • Sentence case: Capitalize first letter of a sentence, typically used for regular paragraphs.
  • All caps (uppercase): All letters in the text are capitalized, used for emphasis, shouting, or when specific stylistic choices are desired.

While some informal contexts might disregard strict capitalization rules, understanding the reasons behind them helps you make informed choices about usage and maintain clarity, professionalism, and respect in your writing.

All caps (uppercase)

In Swift, you can convert a string to all caps (uppercase) using the uppercased() method. It’s important to note that uppercased() does not modify the original string; it returns a new string with the uppercase transformation. If you want to modify the original string, you need to assign the result back to the original variable.

let str = "hello world"
let newStr = str.uppercased()
print(newStr) // HELLO WORLD

Capitalizing the first letter of each word

The capitalized property of a string in Swift returns a new string with the first character of each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.

import Foundation

let str = "hello WOrlD"
let newStr = str.capitalized
print(newStr) // Hello World

The reason why all remaining characters are set to their corresponding lowercase is to follow the convention of title case, which is a common way of formatting the words in a title or a headline.

Title case usually capitalizes the first letter of each word, and lowercases the rest of the letters, except for some exceptions such as proper nouns, acronyms, or words that are entirely in uppercase.

Capitalizing the first letter of sentence

If you only want to uppercase the very first letter and leave the rest unchanged, you can use the following approach:

let str = "hello world"
let newStr = str.prefix(1).uppercased() + str.dropFirst()
print(newStr) // Hello world

The uppercased() method returns a new string with all the characters in the original string converted to uppercase. You can use it to compare two strings regardless of their case, or to transform a string to uppercase for display purposes.

The dropFirst() method returns a new string with the specified number of characters removed from the beginning of the original string. You can use it to manipulate strings by removing prefixes or unwanted characters.