在SwiftUI中,尝试给数组赋值时,发生报错:
inputs.first(where: { $0.id == symbol})?.value = string ?? "" // 报错行
报错信息:
Cannot assign to property: function call returns immutable value
这个报错的原因为Swift中的first(where:)返回的是常量(immutable)值的拷贝,不能直接修改它的属性。
解决方案:用 firstIndex(where:) 查找可变引用。
if let index = inputs.firstIndex(where: { $0.id == symbol }) {
inputs[index].value = string ?? ""
}
为什么 first(where:)?.value = … 不行?
因为 first(where:) 返回的是一个结构体的副本(CurrencyInput 是 struct),不能修改这个副本的属性,它是只读的。