如何将@escaping闭包函数的结果保存到变量中?

时间:2017-09-19 12:29:46

标签: swift callback closures

我目前有一个课程如下:

class Anton {

    //URL to web service (Internal)
    let URL_DISPLAY_MENU = "http://192.168.1.100/api/DisplayMenu.php"

    func displayMenu(completion: @escaping ([[String:Any]]) ->()) {
        let requestURL = URL(string: URL_DISPLAY_MENU)
        var request = URLRequest(url: requestURL!)
        request.httpMethod = "POST"
        var menu: [[String:Any]]?


        let task = URLSession.shared.dataTask(with: request) { data,response,error in guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
            }
            do {
                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                } else {
                    menu = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] ?? []
                    var dictionary = [Int:Any]()
                    for (index,item) in menu!.enumerated() {
                        let uniqueID = index
                        dictionary[uniqueID] = item
                    }
                    completion(menu!)
                }
            } catch let error as NSError {
                print(error)
            }

        }
        task.resume()
    }
}

目前我使用的课程&包含的功能如下:

var anton = Anton()

anton.displayMenu { menu in
            print(menu)
}

我想要做的是将@escaping结果保存到全局变量中。我很擅长逃避关闭,所以不确定如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

您可以直接在完成时保存您的价值。

示例:

var anton = Anton()

anton.displayMenu { menu in
    self.myMenu = menu
}