我尝试将字符串中每个单词的第一个字母大写,我有以下代码:
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
}
但是,我收到以下错误:
不能在不可变值上使用变异成员:'word'是'let'常量。
我尝试在单词(var word)
之前添加var,但我收到错误:
参数可能没有'var'说明符。
我该如何解决这个问题?
答案 0 :(得分:5)
制作本地可变副本:
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
}