如何在完成处理程序中使用完成处理程序

时间:2021-03-28 19:31:18

标签: swift

我将完成处理程序的类型别名如下,在完成处理程序中有一个完成处理程序。

typealias voidCompletionHandler = () -> Void
typealias dataCompletionHandler = (Data, [String: String], voidCompletionHandler) -> Void

我想使用计算属性来定义完成处理程序。

var completion: dataCompletionHandler {
    return { data, _, completion in
        jsonDataProcess(data: data) { json in // ERROR --> This is SwiftyJSON process with completion handler.
            if json != nil {
            Country.instantiate(json: json!) {. // ERROR --> The is Core Data process with completion handler
                completion()
            }
        }
    }
}

使用上面的代码,我得到“转义闭包捕获非转义参数‘完成’。

子进程也有@escaping 所以,它们不是问题。就是dataCompletionHandler里面的completion handler,不知道怎么定义为@escaping。

// Inside JSON Handler class
func jsonDataProcess(data: Data, completion: @escaping jsonCompletionHandler) {
    do {
        let json = try JSON(data: data)
        if json["Status"].string == "Success" {
            completion(json["Data"])
        } else {
            completion(nil)
        }
    } catch {
        print(error)
        completion(nil)
    }
}

// Inside Country Class
static func instantiate(json: JSON, completion: @escaping voidCompletionHandler) {
    container.performBackgroundTask { (context) in
        let country = Country(context: context)
        country.name = json["name"].string
        country.iso2digit = json["alpha-2"].string
        country.iso3digit = json["alpha-3"].string
        country.region = json["region"].string
        try? context.save()
        print("Country.instantiate : \(String(describing: json["alpha-2"].string))")
        completion()
    }
}

作为计算属性使用时,如何将完成处理程序中的完成处理程序设为@escaping?

1 个答案:

答案 0 :(得分:0)

使转义声明成为类型别名的一部分。