Search code examples
iosswiftsegue

performSegueWithIdentifier - Cannot convert value of type 'AnyObject' to argument type 'AnyObject?'


I am trying to pass some string data to a viewcontroller using performSegueWithIdentifier, but I get this error Cannot convert value of type 'AnyObject?'. Type(Aka'Optional<AnyObject>.Type) to expected argument type 'AnyObject?' Even if I use sender:self, it still does not work. In the storyboard, the segue is made by dragging a segue from 1st to 2nd view controller.

@IBAction func resetPassword(sender: AnyObject) {



    FIRAuth.auth()?.sendPasswordResetWithEmail(emailTextField.text!, completion: { (error) in

        var customError = error?.localizedDescription

            if error == nil {

                let noError = "Click on the link received in the email"
                self.emailTextField.text = ""
                self.emailTextField.attributedPlaceholder = NSAttributedString(string: noError, attributes:[NSForegroundColorAttributeName: UIColor.blueColor()])
                self.customErroSent = noError

            performSegueWithIdentifier("fromSeventhToFifth", sender: AnyObject?)

                //self.resetButtonOutlet.hidden = true
              //  self.emailTextField.hidden = true

            } else {


                 self.emailTextField.text = ""
                self.emailTextField.attributedPlaceholder = NSAttributedString(string:customError!, attributes:[NSForegroundColorAttributeName: UIColor.redColor()])
            }
        })
    }

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "fromSeventhToFifth" {
        if let destViewController = segue.destinationViewController as? FifthViewController {
                    destViewController.label.text = customErroSent


                }
            }
        }
    }

Solution

  • The sender parameter is of type AnyObject? - so you can supply any object reference or nil, but you can't put AnyObject? since that is a type, not an object.

    The error you are getting when you make this change, Implicit use of 'self' in closure, refers to the invocation of the function performSegueWithIdentifier, not the sender argument.

    Since you are calling the function from within a closure, Swift needs to ensure that the closure captures self i.e. prevents it from being deallocated while the closure still exists.

    Outside the closure this capture isn't necessary as if the object that self refers to has been deallocated the code can't be executing (The code is part of self).

    To capture self, simply refer to it inside the closure:

    self.performSegueWithIdentifier("fromSeventhToFifth", sender: self)
    

    or

    self.performSegueWithIdentifier("fromSeventhToFifth", sender: nil)