简体   繁体   English

如何获取在闭包中分配的变量的值(Swift)

[英]How to get the value of the variable that is assigned in a closure (Swift)

I'm using the Twitter REST API in Swift, and I am trying to get the value of a variable that is assigned inside of a Twitter Request closure, so that I can use that value outside of the closure. 我正在Swift中使用Twitter REST API,并且试图获取在Twitter Request闭包内分配的变量的值,以便可以在闭包外使用该值。

I acquired this code from the Twitter REST API tutorial for Swift, located at: https://dev.twitter.com/twitterkit/ios/access-rest-api 我从Swift的Twitter REST API教程中获得了此代码,该教程位于: https : //dev.twitter.com/twitterkit/ios/access-rest-api

func jsonAvailable() -> Bool {
    // Swift
    let client = TWTRAPIClient()
    let statusesShowEndpoint = "https://api.twitter.com/1.1/statuses/show.json"
    let params = ["id": "20"]
    var clientError : NSError?

    var jsonAvailable: Bool = false
    let request = client.urlRequest(withMethod: "GET", url: 
    statusesShowEndpoint, parameters: params, error: &clientError)

    client.sendTwitterRequest(request) { (response, data, connectionError)-> Void in
    if connectionError != nil {
        print("Error: \(connectionError)")
    }

    do {
        let json = try JSONSerialization.jsonObject(with: data!, options: [])
        print("json: \(json)")
        jsonAvailable = true
    } catch let jsonError as NSError {
        print("json error: \(jsonError.localizedDescription)")
    }

    print("Value of jsonAvailable: \(jsonAvailable)")
    return jsonAvailable
    //always returns false, even if it is changed to true inside of the closure
}

In the last line, jsonAvailable is always false, even when it is changed to true inside of the closure. 在最后一行,即使在闭包内部将jsonAvailable更改为true,它也始终为false。 How can I get the value of jsonAvailable at the end of the function, even as it is modified inside of the sendTwitterRequest closure? 即使在sendTwitterRequest闭包内部进行了修改,如何在函数末尾获取jsonAvailable的值?

I have tried writing this closure in a separate function and then calling the function to get the value, but because it is a custom closure that requires the client to be called by "sendTwitterRequest" I have found it difficult to pass all these required parameters to fit the API. 我尝试在单独的函数中编写此闭包,然后调用该函数以获取值,但是由于这是一个自定义闭包,需要通过“ sendTwitterRequest”调用客户端,因此我很难将所有这些必需的参数传递给适合API。

Thanks for the help! 谢谢您的帮助!

Your closure is async. 您的关闭是异步的。 What happens is that you go through all the function body before sendTwitterRequest assigns true to jsonAvailable , resulting in jsonAvailable being false. 发生的事情是,在sendTwitterRequest将true分配给jsonAvailable之前,您遍历了所有函数体,从而导致jsonAvailable为false。 What you need to do is having a callback instead, providing the json status if you'd like (or the json itself as a nillable object). 您需要做的是拥有一个回调,如果需要的话,提供json状态(或将json本身作为可设置对象)。

EDIT : You could have something like this 编辑 :您可能有这样的事情

func jsonAvailable(callback: ((_ isJsonAvailable: Bool) -> Void)) {
    client.sendTwitterRequest(request) { (response, data, connectionError)-> Void in {
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: [])
            print("json: \(json)")
            callback(true)
        } catch let jsonError as NSError {
            print("json error: \(jsonError.localizedDescription)")
            callback(false)
        }
    }
}

jsonAvailable(callback: { (_ isJsonAvailable: Bool) in
    print(isJsonAvailable)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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