Manuel
Manuel

Reputation: 15042

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.)

Upvotes: 12

Views: 7269

Answers (1)

Vatsal
Vatsal

Reputation: 18171

(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

Upvotes: 26

Related Questions