Cannot convert value of type 'NSObject -> () -> PostFeed' to expected argument type 'AnyObject?'

北慕城南 提交于 2019-11-28 05:44:32

问题


I'm adding a UISwitch in the following way:

  let anonSwitch : UISwitch = {
   let mySwitch = UISwitch()
    mySwitch.on = false
    mySwitch.setOn(false, animated: false);
    mySwitch.tintColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 1.0)
    mySwitch.addTarget(self, action: #selector(handleAnonSwitch), forControlEvents: .ValueChanged)

    return mySwitch
}()

Now I'm getting the following error message on the self keyword in mySwitch.addTarget :

 Cannot convert value of type 'NSObject -> () -> PostFeed' to expected argument type 'AnyObject?'

I use self in all my other addTarget functions for UIButton and I never encounter this error


回答1:


Change your let into a lazy var.

I'm not sure exactly what the compiler is thinking (or where its crazy error message is coming from), but my guess is this:

In Swift, variables which are let have to be initialized before you can use self. One reason for this is that the compiler can't verify that addTarget(action:forControlEvents:) isn't going to try to call anonSwitch() on whatever it gets for target, or do something else, like access a different variable that would be initialized after anonSwitch, that depends on initialization having completed for this object.

Using lazy var means that the compiler can verify that the value assigned to anonSwitch won't be accessed before self is a valid object, because it won't be possible to call anonSwitch until all other members of the class have been initialized.



来源:https://stackoverflow.com/questions/37635411/cannot-convert-value-of-type-nsobject-postfeed-to-expected-argument-t

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