Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign to immutable expression of type 'Bool?'

The compiler throws the error when trying to assign a new value:

Cannot assign to immutable expression of type 'Bool?'

I have a class:

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

In source view controller in prepareForSegue:

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

In destination view controller:

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

I declared items as Any because it can either contain [Items] or [[Items]].

How can I make the variable selected mutable?

(I hope this is not a duplicate question, I found many similar questions, but could not solve this.)

like image 403
Manuel Avatar asked Oct 10 '15 17:10

Manuel


1 Answers

(setting.items as! [Setting.Item]) returns an immutable value. You cannot perform mutating functions on it. What you can, do, however, is put it in a temporary variable, mutate that, and assign it back to your property:

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

temporaryVariable[index].selected = false

setting.items = temporaryVariable
like image 185
Vatsal Manot Avatar answered Sep 28 '22 08:09

Vatsal Manot