有没有一种方法可以从我的结帐中为 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中闭包的方法返回值
发布评论