Swift中闭包的方法返回值 [英] Return value for method from closure in Swift

查看:142
本文介绍了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中闭包的方法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆