lmiguelvargasf lmiguelvargasf - 14 days ago 9
Swift Question

Cannot use mutating member on immutable value inside a closure

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?

Answer

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
}
Comments