1

I try to capitalize the first letter of each word of a string, and I have the following code:

func makeHeadline(string: String) -> String {
        let headline = words.map { (word) -> String in
        var word = word
        let firstCharacter = word.remove(at: word.startIndex)
        return "\(String(firstCharacter).uppercased())\(word)"
        }.joined(separator: " ")

        return headline
    }

However, I get the following error:

Cannot use mutating member on immutable value: 'word' is a 'let' constant.

I tried adding var before word (var word), but I get the error:

Parameters may not have the 'var' specifier.

How can I solve this?

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228

1 Answers1

7

Make a local mutable copy:

func makeHeadline(string: String) -> String {
    let words = string.components(separatedBy: " ")

    let headline = words.map { (word) -> String in
        var word = word
        let firstCharacter = word.removeAtIndex(word.startIndex)
        return String(firstCharacter).uppercaseString + word
    }.joined(separator: " ")

    return headline
}
Alexander
  • 59,041
  • 12
  • 98
  • 151