Learn Courses My Dashboard

Capitalize First Letter in String?

Is there an easy way to just capitalize the first character in a String?

I’m working on the iOS Foundations Module 2 Challenge 12, and I want to display only the first topping’s letter upper-cased. Rather, using the .capitalized string method, it capitalizes every word.

Screen Shot 2021-07-31 at 10.17.01 AM

StackOverflow has people using extensions of the String type, but I don’t understand these. capitalization - How to capitalize the first character of sentence using Swift - Stack Overflow

Otherwise, ideally, I’d like to slice the string like this as Python would do it:
capitalizedString = toppings[0].capitalized + toppings[1:]

let capitalizedString = toppings.prefix(1).uppercased() + toppings.dropFirst()

which you can (should) put in an extension on String to make it easier to work with:

extension String {
    var capitalizedFirstLetter: String {
        self.prefix(1).uppercased() + self.dropFirst()
    }
}

let capitalizedString = toppings.capitalizedFirstLetter
1 Like

Hey thanks for the reply, and clear answer!

I’m surprised that Swift didn’t have a way to do this already, but am glad you can just write this extension in any of your Xcode project, then it becomes a method for any string.