Swift中闭包的方法返回值

编程入门 行业动态 更新时间:2024-10-24 01:48:14
本文介绍了Swift中闭包的方法返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有一种方法可以从我的结帐中为 shouldPerformSegueWithIdentifier 方法返回值?还是应该以其他方式执行此操作?

Is there a way that I can return value for shouldPerformSegueWithIdentifier method from my closure? Or should I do it differently?

override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool { getDataFromSomewhere() { succeeded, data in if succeeded { // Should return true here } else { self.errorAlert("Error", message: "Can't get data...") // Should return false here } } }

推荐答案

您不能使 shouldPerformSegueWithIdentifier:sender: 从您放置的点返回//应该在此处返回true 。您需要改为执行以下操作:

You can't make shouldPerformSegueWithIdentifier:sender: return from the point where you put // Should return true here. You need to do something like this instead:

override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool { var returnValue: Bool = false getDataFromSomewhere() { succeeded, data in if succeeded { returnValue = true } else { self.errorAlert("Error", message: "Can't get data...") returnValue = false } } return returnValue }

请注意,仅当 getDataFromSomewhere 在 getDataFromSomewhere 返回之前执行关闭。如果 getDataFromSomewhere 存储闭包,并安排稍后再调用它(例如,在异步网络请求之后),则此方法将无效。它将使 shouldPerformSegueWithIdentifier:sender:返回用于初始化 returnValue 的值。

Note that this will only work if getDataFromSomewhere executes the closure before getDataFromSomewhere returns. If getDataFromSomewhere stores the closure, and arranges for it to be called later on (after an asynchronous network request, for example), then this won't work. It will just make shouldPerformSegueWithIdentifier:sender: return the value you used to initialize returnValue.

更多推荐

Swift中闭包的方法返回值

本文发布于:2023-11-26 18:30:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634697.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值   方法   Swift   中闭包

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!