错误:“无法分配给'Bool'类型的不可变表达式"? [英] Error: "Cannot assign to immutable expression of type 'Bool'"?

查看:106
本文介绍了错误:“无法分配给'Bool'类型的不可变表达式"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何解决?我是新编码员.谢谢

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

我收到以下错误:

无法分配给'布尔'类型的不可变表达式"

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

当我尝试将"isSelected"设置为falsetrue

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

    }
}

推荐答案

出现此错误是因为将发件人转换为AnyObject时会得到immutable类型的对象,因此无法更新其属性,最佳选择解决您的问题的方法是将发件人声明从Any更改为实际的UIControl意味着如果它是按钮,则将UIButton.

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
}

如果您仍要使用Any,则将发件人转换为它所属的实际UIControl.

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
    }
}    

这篇关于错误:“无法分配给'Bool'类型的不可变表达式"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆