performSegueWithIdentifier - 无法将'AnyObject'类型的值转换为参数类型'AnyObject?'

时间:2016-07-06 23:35:05

标签: ios swift segue

我正在尝试使用performSegueWithIdentifier将一些字符串数据传递给viewcontroller,但是我收到此错误Cannot convert value of type 'AnyObject?'. Type(Aka'Optional<AnyObject>.Type) to expected argument type 'AnyObject?' 即使我使用sender:self,它仍然无效。 在故事板中,通过将segue从第一个视图控制器拖动到第二个视图控制器来制作segue。

@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


                }
            }
        }
    }

3 个答案:

答案 0 :(得分:1)

sender参数的类型为AnyObject? - 因此您可以提供任何对象引用或nil,但您不能放置AnyObject?,因为这是类型,而不是对象。

进行此更改时出现的错误,隐式使用&#39; self&#39;在闭包中,指的是函数performSegueWithIdentifier的调用,而不是sender参数的调用。

由于您是在闭包内调用函数,因此Swift需要确保闭包捕获 self,即在闭包仍然存在时阻止它被解除分配。

在闭包之外,这个捕获是不必要的,好像self引用的对象已被解除分配,代码无法执行(代码是self的一部分)

要捕获self,只需在闭包中引用它:

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

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

答案 1 :(得分:0)

AnyObject?是可选类型。您应该将其设置为nil或Class的任何实例。例如:

performSegueWithIdentifier("fromSeventhToFifth", sender: nil)
performSegueWithIdentifier("fromSeventhToFifth", sender: slef)

答案 2 :(得分:0)

Swift 4.0,在TableView项目模板中。 声明:

// MARK: - Segues
    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == "fromSeventhToFifth" {
            if let indexPath = tableView.indexPathForSelectedRow
            {

            }
        }
    }

致电:

performSegue(withIdentifier: "fromSeventhToFifth", sender: self)