Swift apply .uppercaseString to only the first letter of a string

SomeGuy picture SomeGuy · Oct 10, 2014 · Viewed 140.1k times · Source

I am trying to make an autocorrect system, and when a user types a word with a capital letter, the autocorrect doesn't work. In order to fix this, I made a copy of the string typed, applied .lowercaseString, and then compared them. If the string is indeed mistyped, it should correct the word. However then the word that replaces the typed word is all lowercase. So I need to apply .uppercaseString to only the first letter. I originally thought I could use

nameOfString[0]

but this apparently does not work. How can I get the first letter of the string to uppercase, and then be able to print the full string with the first letter capitalized?

Thanks for any help!

Answer

Kirsteins picture Kirsteins · Oct 10, 2014

Including mutating and non mutating versions that are consistent with API guidelines.

Swift 3:

extension String {
    func capitalizingFirstLetter() -> String {
        let first = String(characters.prefix(1)).capitalized
        let other = String(characters.dropFirst())
        return first + other
    }

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

Swift 4:

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

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