How to Capitalize Only the First Letter in Swift

How to Capitalize Only the First Letter in Swift

Written by

in

Quick answer: To capitalize only the first letter of a Swift String, combine prefix(1).uppercased() with dropFirst(). Wrapping this in a StringProtocol extension works on both String and Substring, handles empty strings safely, and leaves the rest of the text unchanged.

Why this happens

Two common surprises trip developers up when trying to uppercase only the first character of a String in Swift.

First, integer subscripting like myString[0] does not compile in Swift. Swift strings are collections of Character values backed by extended grapheme clusters rather than fixed-width bytes. Because one visible character can span multiple Unicode scalars, finding the nth character is not a constant-time operation, so Swift requires String.Index instead of Int.

Second, Foundation’s built-in .capitalized property does more than change the first character. Calling "hello world".capitalized produces "Hello World", and calling "iPhone".capitalized produces "Iphone" because .capitalized uppercases the start of every word and lowercases all remaining letters. When you only want to change the very first character—such as restoring capitalization after an autocorrect lookup or formatting a sentence—you need to split the first character from the rest of the string.

How to fix it

1. Add a StringProtocol extension (recommended)

Extending StringProtocol instead of String lets your helper work on both String and Substring values without extra conversions. Using prefix(1) and dropFirst() is also safe on empty strings: prefix(1) returns an empty Substring, and dropFirst() returns an empty Substring, so the result is "" with no out-of-bounds crash.

import Foundation

extension StringProtocol {
    var firstUppercased: String {
        prefix(1).uppercased() + dropFirst()
    }

    var firstCapitalized: String {
        prefix(1).capitalized + dropFirst()
    }
}

Use firstUppercased for standard uppercase behavior and firstCapitalized when you want title-case handling for Unicode digraph characters (such as "Dž" instead of "DŽ"):

let sentence = "hello world!!!".firstUppercased
// "Hello world!!!"

let brand = "iPhone".firstUppercased
// "IPhone" (preserves "Phone")

let empty = "".firstUppercased
// ""

let digraph = "dž".firstCapitalized
// "Dž"

If you want the first letter uppercased and every remaining character forced to lowercase—for example, normalizing a mistyped word from an autocorrect dictionary—append .lowercased() to dropFirst():

extension StringProtocol {
    var sentenceCased: String {
        prefix(1).uppercased() + dropFirst().lowercased()
    }
}

let fixed = "hELLO wORLD".sentenceCased
// "Hello world"

2. Add mutating and non-mutating String methods

If your codebase prefers explicit methods that follow the Swift API Design Guidelines (an -ing form for returning a new value, and an imperative verb for mutating in place), define both on String:

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

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

You can then choose whichever form fits the call site:

let original = "swift"
let updated = original.capitalizingFirstLetter() // "Swift"

var mutableWord = "xcode"
mutableWord.capitalizeFirstLetter() // "Xcode"

3. Capitalize inline without an extension

For a one-off transformation where you do not want to add a project-wide extension, combine first with dropFirst() directly:

func uppercaseFirstCharacter(of text: String) -> String {
    guard let first = text.first else { return "" }
    return String(first).uppercased() + text.dropFirst()
}

If you need to mutate a large String in place using String.Index, you can replace just the first character range:

var word = "autocorrect"
if let first = word.first {
    let range = word.startIndex..<word.index(after: word.startIndex)
    word.replaceSubrange(range, with: String(first).uppercased())
}

This avoids creating an intermediate copy of the entire tail of the string when word is long.

How to prevent it

  • Avoid myString[0] in Swift: Always use first, prefix(_:), dropFirst(), or String.Index methods instead of integer subscripts.
  • Reserve .capitalized for title-casing words: Remember that String.capitalized alters every word boundary and lowercases interior uppercase letters like iOS or SwiftUI.
  • Prefer StringProtocol for read-only helpers: Extending StringProtocol ensures slices (Substring) from split, prefix, or dropFirst work without wrapping them in String(...) first.
  • Test with empty strings and emoji: Using prefix(1) and dropFirst() guarantees you never hit a fatal index-out-of-bounds error on "" or split a multi-scalar emoji.

FAQ

Why doesn’t myString[0] work in Swift?

Swift String values are indexed by String.Index rather than Int because each Character is an extended grapheme cluster that can occupy a variable number of bytes in memory. Using prefix(1), first, or startIndex keeps character boundaries intact.

What is the difference between uppercased() and capitalized on the first letter?

For standard ASCII letters, prefix(1).uppercased() and prefix(1).capitalized return the same result. For certain Unicode digraphs like dž, capitalized produces the title-case character Dž whereas uppercased() produces DŽ.

Will prefix(1).uppercased() + dropFirst() crash on an empty string?

No. Both prefix(1) and dropFirst() are safe on empty collections and return an empty Substring, so the expression evaluates cleanly to "".

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.