【问题标题】:How to save the result of a @escaping closure function into a variable?如何将@escaping 闭包函数的结果保存到变量中?
【发布时间】:2017-09-19 12:29:45
【问题描述】:

我目前有以下课程:

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 结果保存到全局变量中。我对逃避闭包很陌生,所以不知道该怎么做。

【问题讨论】:

  • 但是@escaping ([[String:Any]]) ->() 没有结果。 ->() 表示它是无效的。你到底指的是什么结果?
  • 啊,我想我的函数出错了,我想要的本质上是,从 Anton 类中的那个函数中,我想返回菜单变量。然后,当我在另一个类中的其他位置调用该函数时,我想全局保存该变量。

标签: swift callback closures


【解决方案1】:

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

例子:

var anton = Anton()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 2023-03-06
    • 1970-01-01
    • 2017-05-12
    相关资源
    最近更新 更多