3
votes

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

1 Answers

12
votes

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.