从swift中得到variables的值

所以我有一个closures调用任务这是一个post请求,我有一个全局variables称为值,我试图设置“值”的值是我从数据库中检索数据存储在一个名为“数组”。 不要担心tableview.reloadData部分,这已经完成了。 我只想知道如何从封闭中获得价值。

var values:NSArray = [] @IBOutlet weak var Open: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() Open.target = self.revealViewController() Open.action = #selector(SWRevealViewController.revealToggle(_:)) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) get() print ("values=\(values)") } func get(){ let request = NSMutableURLRequest(URL: NSURL(string: "http://www.percyteng.com/orbit/getAllpostsTest.php")!) request.HTTPMethod = "POST" let postString = "user=\("ios")" request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print("error=\(error)") return } print("response = \(response)") let array = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray dispatch_async(dispatch_get_main_queue()) { [unowned self] in self.values = array print ("error=\(self.values)") self.tableView?.reloadData(); } } task.resume() 

在闭包中使用任何asynchronous任务的完成

 func get(completion:(value: NSArray) -> Void){ // request part let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in // your serialization code dispatch_async(dispatch_get_main_queue()) { [unowned self] in self.values = array // return value to completion completion(value: array) print ("error=\(self.values)") self.tableView?.reloadData(); } } } 

改变你在viewdidload中获取值的方式

  get{(value) in // finish NSURLSession task and everything should be done in this closure self.values = value print ("values=\(self.values)") }