Error: “Cannot assign to immutable expression of type 'Bool'”?

本秂侑毒 提交于 2019-12-11 01:35:45

问题


How do I fix this? I'm a new coder. Thank you

I get the follow error:

"Cannot assign to immutable expression of type 'Bool'"

When I try to set the "isSelected" to false and true

@IBAction func onFilter(_ sender: Any) {

    if ((sender as AnyObject).isSelected == true) {

        hideSecondaryMenu()
        (sender as AnyObject).isSelected = false

    } else {

        showSecondaryMenu()
        (sender as AnyObject).isSelected = true

    }
}

回答1:


You are getting this error because when you are converting sender to AnyObject you are getting immutable type object so you cannot update its properties, The best option to solved your problem is to change your sender declaration from Any to actual UIControl means if it is button then UIButton.

@IBAction func onFilter(_ sender: UIButton) {
    hideSecondaryMenu()
    sender.isSelected = !sender.isSelected
}

If you want to still use Any then convert sender to actual UIControl that it is belong to.

@IBAction func onFilter(_ sender: Any) {
    if sender is UIButton {
         let btn = sender as! UIButton
         hideSecondaryMenu()
         btn.isSelected = !btn.isSelected
    }
}    


来源:https://stackoverflow.com/questions/40880694/error-cannot-assign-to-immutable-expression-of-type-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!