尝试分配新值时,编译器会抛出错误:
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]].
如何使变量选择为可变?
(我希望这不是一个重复的问题,我发现了许多类似的问题,但无法解决这个问题.)
(setting.items as![Setting.Item])返回一个不可变的值.你不能在它上面执行变异功能.然而,你可以做什么,把它放在一个临时变量中,改变它,并将它分配回你的财产:
原文链接:https://www.f2er.com/swift/319186.htmlvar temporaryVariable = (setting.items as! [Setting.Item]) temporaryVariable[index].selected = false setting.items = temporaryVariable