问题
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