Swift access data outside closure

前端 未结 1 550
误落风尘
误落风尘 2021-01-14 08:55

I am newbie to iOS. I have query that how can we access data or variables inside closure. Following is my code snippet.

self.fetchData() { data in
       dis         


        
相关标签:
1条回答
  • 2021-01-14 09:23

    You should employ completion handler closure in the function that calls fetchData, e.g.:

    func fetchString(completionHandler: (String?) -> ()) {
        self.fetchData() { responseData in
            dispatch_async(dispatch_get_main_queue()) {
                println("Finished request")
                if let data = responseData { // unwrap your data (!= nil)
                    let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
                    completionHandler(responseString)
                } else {
                    completionHandler(nil)
                }
            }
        }      
    }
    

    And you'd call it like so:

    fetchString() { responseString in
        // use `responseString` here, e.g. update UI and or model here
    
        self.myString = responseString
    }
    
    // but not here, because the above runs asynchronously
    
    0 讨论(0)
提交回复
热议问题