gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:09:02 26 4
gpt4 key购买 nike

我目前有一个类(class)如下:

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 结果保存到全局变量中。我对逃避关闭非常陌生,所以不知道如何解决这个问题。

最佳答案

完成后可以直接保存你的值。

示例:

var anton = Anton()

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

关于swift - 如何将 @escaping 闭包函数的结果保存到变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46300517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com