Ios 如何更改数组中的所有元素?
我试图修改数组中的元素。但它说“不能赋值:“$0”是不可变的”有人知道如何解决它吗 我的代码:Ios 如何更改数组中的所有元素?,ios,arrays,swift,Ios,Arrays,Swift,我试图修改数组中的元素。但它说“不能赋值:“$0”是不可变的”有人知道如何解决它吗 我的代码: boxes.filter({ $0.color == currentColor }).forEach{ switch newColor { case .blue: // This assisgnments return error. $0 = Blue() case .purple: $0 = Purple() case
boxes.filter({ $0.color == currentColor }).forEach{
switch newColor {
case .blue:
// This assisgnments return error.
$0 = Blue()
case .purple:
$0 = Purple()
case .red:
$0 = Red()
case .yellow:
$0 = Yellow()
}
}
谢谢。您的代码的问题是,您在forEach$0中获得的元素是数组中元素的不可变副本,因此您不仅不能更改它们,而且如果可以,您也不会更改数组中的元素,而是更改它们的副本 要实际更改数组的内容,您需要使用索引直接访问数组中的元素,假定元素本身及其属性是可变的
for index in 0..<boxes.count {
if boxes[index].color == currentColor {
switch newColor {
case .blue:
boxes[index].color = Blue()
case .purple:
boxes[index].color = Purple()
case .red:
boxes[index].color= Red()
case .yellow:
boxes[index].color = Yellow()
}
}
}
到
依此类推,我不确定在此上下文中蓝色是什么,但解决方案仍然有效。您的代码的问题是,您在forEach$0中获得的元素是数组中元素的不可变副本,因此您不仅不能更改它们,而且如果可以,您不会更改数组中的元素,而是更改它们的副本 要实际更改数组的内容,您需要使用索引直接访问数组中的元素,假定元素本身及其属性是可变的
for index in 0..<boxes.count {
if boxes[index].color == currentColor {
switch newColor {
case .blue:
boxes[index].color = Blue()
case .purple:
boxes[index].color = Purple()
case .red:
boxes[index].color= Red()
case .yellow:
boxes[index].color = Yellow()
}
}
}
到
以此类推,我不确定在这种情况下蓝色是什么,但解决方案仍然有效。因为其中一个答案提到了map,但没有说明如何更新/覆盖原始的Box数组,我想我也应该添加一个答案 如果要基于当前颜色修改原始阵列,可以使用以下贴图:
boxes = boxes.map { box in
guard box.color == currentColor else {
return box
}
switch newColor {
case .blue: return Blue()
case .purple: return Purple()
case .red: return Red()
case .yellow: return Yellow()
default: return box // or a different default that suits your needs
}
}
因为其中一个答案提到map,但没有显示如何更新/覆盖原始box数组,所以我想我也应该添加一个答案 如果要基于当前颜色修改原始阵列,可以使用以下贴图:
boxes = boxes.map { box in
guard box.color == currentColor else {
return box
}
switch newColor {
case .blue: return Blue()
case .purple: return Purple()
case .red: return Red()
case .yellow: return Yellow()
default: return box // or a different default that suits your needs
}
}
您可以通过索引访问和修改ElementsTable继续使用枚举:
您可以通过索引访问和修改ElementsTable继续使用枚举:
boxes.enumerated().forEach { (offset, element) in
guard element.color != currentColor else { return }
switch newColor {
case .blue:
boxes[offset] = Blue()
case .purple:
boxes[offset] = Purple()
case .red:
boxes[offset] = Red()
case .yellow:
boxes[offset] = Yellow()
}
}