【问题标题】:How to use a completion handler inside the completion handler如何在完成处理程序中使用完成处理程序
【发布时间】:2021-03-28 19:31:18
【问题描述】:

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

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?

【问题讨论】:

    标签: swift


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-03
      • 2015-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      相关资源
      最近更新 更多