Self.navigationController? .PopViewControllerAnimated by UIAlertController

I'm new to speed, but I think I'm cheating on everything. This greatly impeded my progress.

I want to do this in order to display an error message to the user when we cannot find the corresponding data in his query, and then go to the previous ViewController.

However, I am having real problems with this. In the line where I add the action, I get the following error: "UIViewController?" 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 can I do it? Am I missing something? I tried messing with the outdated UIAlertView, but did not become wiser.

+6
source share
1 answer

Just add an explicit return to the closure body:

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

The reason this happens is because one statement closure is treated as a return value, so the compiler uses the return value popViewControllerAnimated , which is not surprising - is it a UIViewController? . The explicit return statement avoids this.

This behavior is documented in Implicit returns from single-expression closures.

+23
source

Source: https://habr.com/ru/post/977774/


All Articles