基本上我有一个功能。我还有另一个具有完成处理程序的函数。在继续第一个功能的行之前,我需要第二个功能的结果。我尝试了Dispatch小组,但是没有用。
func parseData(from json: [String: Any) -> Val {
var a //some values I got from parsing that I NEED for B
var anotherVariable
B(a) { result in
anotherVariable = result
}
var otherVar = anotherVariable[0]
return Val(a, anotherVariable, otherVar) // this is a struct
//returned
}
func B(_ a: a, completion: @escaping ([Res]) -> Void) {
let group = DispatchGroup()
var res = [Res]()
SomeotherFunc(a, completion: { resp in
res = resp
group.leave()
})
group.notify(queue: .main) {
completion(res)
}
}
答案 0 :(得分:0)
尝试此解决方案。它正在工作
func parseData(from json: [String: Any) -> Val {
var a //some values I got from parsing that I NEED for B
var anotherVariable
let group = DispatchGroup()
group.enter()
B(a) { result in
anotherVariable = result
group.leave()
}
group.wait()
var otherVar = anotherVariable[0]
return Val(a, anotherVariable, otherVar) // this is a struct
//returned
}
func B(_ a: a, completion: @escaping ([Res]) -> Void) {
SomeotherFunc(a, completion: { resp in
completion(res)
})
}
答案 1 :(得分:0)
不要那样做。
请学习了解异步数据处理的工作原理,并在parseData
中添加另一个完成处理程序。而且您在DispatchGroup
中滥用B
。顾名思义,它仅对异步调用的 group 组有用,例如在循环中
func parseData(from json: [String: Any], completion: @escaping (Val) -> Void) {
var a //some values I got from parsing that I NEED for B
var anotherVariable
B(a) { result in
anotherVariable = result
completion(Val(a, anotherVariable, anotherVariable[0]))
}
}
func B(_ a: a, completion: @escaping ([Res]) -> Void) {
var res = [Res]()
SomeotherFunc(a) { resp in
res = resp
completion(res)
})
}