无法分配给 属性:'$0' 是不可变的

Cannot assign to property: '$0' is immutable

我的 table 视图中有默认选择的单元格。我想在点击时更改此选定语言,但无法这样做。我在“$0”行遇到错误:

var languageViewModel = LanguageViewModel()
var languageTitles: [LanguageModel] = []
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var item = languageTitles[indexPath.row]
    var value = item.isSelected
    // Edit isSelected property and refresh table
    languageTitles.forEach { [=11=].isSelected = false  }
    item.isSelected = !value
    tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return languageCell(indexPath: indexPath)
}
private func languageCell(indexPath: IndexPath) -> LanguageTableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: LanguageTableViewCell.identifier, for: indexPath) as! LanguageTableViewCell
    let item = languageTitles[indexPath.row]
    if item.isSelected {
        cell.setupSelected(item)
    } else {
        cell.setup(item)
    }
    return cell
}

struct LanguageModel {
    let language: Language
    var isSelected: Bool = false
}

class LanguageViewModel {
    var locales: [Language] = [.tr, .eng, .az] //.ar
    var currentLanguage = UserDefaultsUtil.getDeviceLanguage()
    var languages: [LanguageModel] = []
    func getLanguageTitles() {
        languages = [
            LanguageModel(language: .tr, isSelected: currentLanguage == locales[0].code),
            LanguageModel(language: .eng, isSelected: currentLanguage == locales[1].code),
            LanguageModel(language: .az,  isSelected: currentLanguage == locales[2].code)
        ]
    }
}

当我想更改语言时无法点击另一个单元格。它总是从视图模型中选择的

如果我将 didselectrowat 更改为

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var item = languageTitles[indexPath.row]
    var value = item.isSelected
    // Edit isSelected property and refresh table
    for languageTitle in languageTitles {
        languageTitle.isSelected = false
    }
    item.isSelected = !value
    tableView.reloadData()
}

无法分配给 属性:'languageTitle' 是一个 'let' 常数

替换为:

        languageTitles.forEach { [=10=].isSelected = false  }

与:

for index in languageTitles.indices {
    languageTitles[index].isSelected = false
}

forEach 有各种微妙而令人惊讶的行为。通常最好改用 for-in。但关键问题是 LanguageModel 是一个结构并且具有值语义。当您将它分配给一个变量(即 $0,或 for-in 循环中的变量)时,会生成一个副本。如果您对副本进行更改,它们不会修改数组。 (默认情况下,它们是常量,所以您无论如何都不能修改它们。)但是,通过下标运算符进行赋值会达到您的预期。