提问者:小点点

如何改变数组内部的所有元素? [副本]


我正在尝试修改数组内部的元素。 但是它说“不能赋值:'$0'是不可变的”,有没有人知道如何解决这个问题。

我的代码:

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()
    }
}

谢了。


共3个答案

匿名用户

代码的问题在于,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()
        }
    }
}

可能交换机中的分配需要从

boxes[index].color = Blue()

boxes[index] = Blue()

等等,我不确定blue()在此上下文中是什么,但该解决方案仍然有效。

匿名用户

由于其中一个答案提到了map,但没有显示如何更新/覆盖原始的boxes数组,我想我也要添加一个答案。

如果要根据当前颜色修改原始数组,可以使用map,如下所示:

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
  }
}

匿名用户

您可以使用enumerated()按索引继续访问和修改元素(可变):

 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()
     }
 }