问题描述
func fetchParseNSyncJson2(parseNSyncFunction: @escaping(String)->Void) {
if 200 == 200 {
print("Got the json")
parseNSyncFunction("The json data")
}
}
func parseNSync2(jsonDictionary: String) {
print("Parsed the data: \(jsonDictionary)")
}
fetchParseNSyncJson2(parseNSyncFunction: parseNSync2(jsonDictionary:))
上面的代码工作正常,但我想向 parseNSync2 函数添加另一个参数来转义闭包,就像这样
func parseNSync2(jsonDictionary: String,done: @escaping(Bool)->Void {
print("Parsed the data: \(jsonDictionary)")
}
然后我想像上面那样在 fetchParseNSyncJson2 函数中传递这个新函数 (带有转义块),我可以吗??
func fetchParseNSyncJson(parseNSyncFunction: (json: String,done: (Bool)->Void)) {
if 200 == 200 {
print("got the json")
parseNSyncFunction(json: "json data",done: (_:)) // how should i pass parameter here??
}
}
func parseNSync(_ jsonDictionary: String,done: @escaping (Bool)->Void) {
print("Parsed: \(jsonDictionary)")
}
fetchParseNSyncJson(parseNSyncFunction: parseNSync(json:,done: { done in // how to i pass parameter here
if done {
print("Done")
}
}))
解决方法
您可以尝试以下方法 -
import Foundation
typealias DoneBlock = ((_ success: Bool) -> Void)
typealias ParseNSyncBlock = ((_ json: String,_ done: @escaping DoneBlock) -> Void)
func fetchParseNSyncJson(parseNSyncBlock: @escaping ParseNSyncBlock) {
if 200 == 200 {
print("got the json")
parseNSyncBlock("the json",{ success in
print("success : \(success)")
})
}
}
func parseNSync(_ json: String,_ done: @escaping DoneBlock) {
print("Parsed: \(json)")
done(true)
}
fetchParseNSyncJson(parseNSyncBlock: parseNSync)
输出
got the json
Parsed: the json
success : true