NEW: Master Swift design patterns with my latest book! >>

How to capitalize the first letter of a string

Written by Paul Hudson    @twostraws

If you want to capitalize the first letter of a string without touching the rest of the letters, add this simple extension of String:

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

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

Here’s an example to try it out:

let test = "the rain in Spain"
print(test.capitalizingFirstLetter())

Available from iOS 8.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Master iOS 11 now!

My book Practical iOS 11 gives you seven complete coding projects that teach all the major new features in iOS 11 in a smart, practical way.

Click here to visit the Hacking with Swift store >>