简体   繁体   中英

self.navigationController?.popViewControllerAnimated from UIAlertController

I'm new to swift but I think I'm getting a hang of it. This stumped my progress pretty hard though.

What I want to do is to throw an error message to the user when we can't find relevant data to his query, and then proceed to take him back to the previous ViewController.

However, I'm having real trouble doing this. On the line where I add the action I get the following error: 'UIViewController?' is not a subtype of Void

let alertController = UIAlertController(title: "Oops", message: "We couldn't find any data for this title, sorry!", preferredStyle: UIAlertControllerStyle.Alert)

alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
    self.navigationController?.popViewControllerAnimated(true)   
}))

How do I do this? Am I missing something obvious? I tried messing around with the deprecated UIAlertView but became none the wiser.

Just add an explicit return statement in the closure body:

alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
    self.navigationController?.popViewControllerAnimated(true)
    return
}))

The reason why that happens is that a single statement closure is handled as the return value, so the compiler uses the return value of popViewControllerAnimated , which unsurprisingly is a UIViewController? . The explicit return statement avoids that.

This behavior is documented in Implicit Returns from Single-Expression Closures

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM