Loading...

How to convert only the first character to uppercase in a string in Swift?

question swift
Ram Patra Published on September 8, 2024

In Swift, you can make the first character of a string uppercase by using built-in string manipulations or by extending the String type. Here’s an example of both approaches:

1. Simple Inline Approach:

You can capitalize the first character like this:

let lowercaseString = "hello world"
let capitalizedString = lowercaseString.prefix(1).capitalized + lowercaseString.dropFirst()
print(capitalizedString) // "Hello world"

2. Using a String Extension:

You can create a String extension to make it reusable:

extension String {
    func capitalizingFirstLetter() -> String {
        return prefix(1).capitalized + dropFirst()
    }

    mutating func capitalizeFirstLetter() {
        self = self.capitalizingFirstLetter()
    }
}

var lowercaseString = "hello world"
let capitalizedString = lowercaseString.capitalizingFirstLetter()
print(capitalizedString) // "Hello world"

Explanation

  • prefix(1) grabs the first character.
  • .capitalized ensures the first letter is capitalized.
  • dropFirst() returns the string without the first character, allowing you to append the rest of the string unchanged.

In Method 2, the reason for having two methods—capitalizingFirstLetter() and capitalizeFirstLetter()—is to provide flexibility in how you manipulate the string:

  1. Non-mutating Method (capitalizingFirstLetter):
    • This method does not modify the original string. Instead, it returns a new string with the first letter capitalized.
    • Use this method when you want to work with a copy of the string, leaving the original string unchanged.
    • Example usage:
      let original = "hello"
      let capitalized = original.capitalizingFirstLetter() // Original remains unchanged.
      
  2. Mutating Method (capitalizeFirstLetter):
    • This method modifies the string it’s called on. It directly changes the original string by capitalizing the first letter.
    • It uses the mutating keyword because it changes the state of the string, which is required for any function that modifies a value type in Swift (like String, which is a value type).
    • Example usage:
      var original = "hello"
      original.capitalizeFirstLetter() // Now `original` is changed.
      

Purpose of mutating

In Swift, types like struct, enum, and String are value types, meaning they are copied when assigned or passed to functions. If you want to modify the value of the instance inside a method (in this case, change the string itself), you need to mark the method as mutating. Without the mutating keyword, the method would not be allowed to alter the original instance, ensuring immutability by default.

By having both options, you provide flexibility depending on whether the original string should be modified or left unchanged.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on September 8, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

June 7, 2020 How to add Global Key Shortcuts to your macOS app using MASShortcut

Adding Global Keyboard Shortcuts to your macOS app can be a pain as there isn’t a Cocoa API for the same. You would have to rely on the old, most of which are deprecated, Carbon API.

question swift November 17, 2023 How do get the string value of an enum in Swift?

In Swift, to get the string value of an enum, you typically have a couple of approaches depending on the enum’s definition. Let’s go through them:

question swiftui swift September 2, 2024 Combine in SwiftUI and how you can rewrite the same code using async await

Combine is Apple’s declarative framework for handling asynchronous events and data streams in Swift. Introduced in SwiftUI and iOS 13, Combine leverages reactive programming principles, allowing developers to process values over time and manage complex asynchronous workflows with clarity and efficiency.

Like my work?

Please, feel free to reach out. I would be more than happy to chat.