Cannot assign immutable expression like "Bool"?

The compiler throws an 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 the source view controller in prepareForSegue :

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

In view 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 the items as "Any" because it can contain [Items] or [[Items]].

How to make the selected variable mutable?

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

+7
immutability swift
source share
1 answer

(setting.items as! [Setting.Item]) returns an immutable value. You cannot perform mutating functions on it. However, you can do this in a temporary variable, modify it, and assign a property to it:

 var temporaryVariable = (setting.items as! [Setting.Item]) temporaryVariable[index].selected = false setting.items = temporaryVariable 
+11
source share

All Articles