我有一个方法正在调用另一个具有完成处理程序的方法。
func getFilesAndDirectories(folder:String) -> Array<Dictionary<String, String>>
{
var returnedResults = Array<Dictionary<String, String>>()
WebService().GetFilesAndDirectories(folder)
{
(result: Array<Dictionary<String, String>>) in
DispatchQueue.main.async {
returnedResults = result
}
}
return returnedResults
}
以下是我如何称呼它:
var filesDirectories = Array<Dictionary<String, String>>()
override func viewDidAppear(_ animated: Bool) {
filesDirectories = getFilesAndDirectories(folder: "/")
print(filesDirectories)
}
但是当我打印filesDirectories时,它会返回[]
我的问题是,如何将getFilesAndDirectories的结果传递给filesDirectories?
答案 0 :(得分:5)
func getFilesAndDirectories(folder:String, completionHandler:@escaping (_ result:Array<Dictionary<String, String>>) -> Void)
{
var returnedResults = Array<Dictionary<String, String>>()
WebService().GetFilesAndDirectories(folder)
{
(result: Array<Dictionary<String, String>>) in
DispatchQueue.main.async {
returnedResults = result
completionHandler(returnedResults)
}
}
}
您可以使用以下相同的
var filesDirectories = Array<Dictionary<String, String>>()
override func viewDidAppear(_ animated: Bool) {
getFilesAndDirectories(folder: "/") { result in
self.filesDirectories = result
print(filesDirectories)
}
}
答案 1 :(得分:2)
你可以这样做:
func getFilesAndDirectories(folder: String, completionHandler: @escaping (_ result: Array<Dictionary<String, String>>) -> ()) {
WebService().GetFilesAndDirectories(folder) {
(result: Array<Dictionary<String, String>>) in
completionHandler(result)
}
}
然后:
override func viewDidAppear(_ animated: Bool) {
getFilesAndDirectories(folder: "/", completionHandler: ({
(result) in
print(result)
}))
}
您应该在completionHandler范围内拥有正确的值。