Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...