Reputation: 69745
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?
Upvotes: 1
Views: 5863
Reputation: 63167
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
}
Upvotes: 7