无法分配给'Bool?'类型的不可变表达式?

时间:2015-10-10 17:03:56

标签: swift immutability

尝试分配新值时,编译器会抛出错误:

Cannot assign to immutable expression of type 'Bool?'

我有一个班级:

class Setting {
   struct Item {
      var text: String
      var selected: Bool?

      init(withText text: String) {
         self.text = text
         self.selected = nil  
      }

   var items: Any

   init(items:Any) {
      self.items = items
   }
}

prepareForSegue中的源视图控制器中:

let item = Setting.Item(withText: user.description)
let setting = Setting(items: [item])
destinationViewController.setting = setting

在目标视图控制器中:

class DestinationViewController: UITableViewController {
   var setting: Setting!
   override func viewDidLoad() {
      super.viewDidLoad()

      //this works
      _ = (setting.items as! [Setting.Item])[index].selected

      // this throws the error
      (setting.items as! [Setting.Item])[index].selected = false
   }
}

我将项目声明为Any,因为它可以包含[Items]或[[Items]]。

如何使变量selected可变?

(我希望这不是一个重复的问题,我发现了很多类似的问题,但无法解决这个问题。)

1 个答案:

答案 0 :(得分:12)

(setting.items as! [Setting.Item])返回一个不可变的值。你不能在它上面执行变异功能。然而,你可以做什么,把它放在一个临时变量中,改变它,并将它分配回你的财产:

var temporaryVariable = (setting.items as! [Setting.Item])

temporaryVariable[index].selected = false

setting.items = temporaryVariable