gpt4 book ai didi

swift - 如何创建一个通用的完成闭包?

转载 作者:行者123 更新时间:2023-11-28 07:40:15 24 4
gpt4 key购买 nike

我有以下协议(protocol):

protocol RESTAPIprotocol {
associatedtype T: Object, Decodable
}

extension RESTAPIprotocol {

func getList(sinceSyncToken: String = "",
pageLimit: Int = 100,
progress: Moya.ProgressBlock? = nil,
completion:@escaping (_ list: [T]?, _ error: AppError?) -> Void) { ... }

和对象:

final class RLMOrganization: RLMDefaults {
typealias T = RLMOrganization
}

final class RLMProject: RLMDefaults {
typealias T = RLMProject
}

final class RLMLocation: RLMDefaults {
typealias T = RLMLocation
}

想像这样使用它:

class SyncEngine {

let listCompletionClosure = { (_ list: [T]?, _ error: AppError?) -> Void in ... }


func syncOrganizations() {
// Sync down from server and update our local DB.
organizationsDAL.getList(sinceSyncToken: organizationsDAL.getLastSyncToken(), completion: listCompletionClosure)
}

但是得到错误:

enter image description here

哪种方式有意义,但不明白我如何将用作 RESTAPIprotocol 一部分的泛型传递到泛型闭包中?

目标是尝试完成以下任务:

func syncOrganizations() {
organizationsDAL.getList(sinceSyncToken: organizationsDAL.getLastSyncToken(), completion: listCompletionClosure)
}

func syncProjects() {
projectsDAL.getList(sinceSyncToken: projectsDAL.getLastSyncToken(), completion: listCompletionClosure)
}

func syncLocations() {
locationsDAL.getList(sinceSyncToken: locationsDAL.getLastSyncToken(), completion: listCompletionClosure)
}

最佳答案

把它改成"怎么样

let listCompletionClosure = { (_ list: [RLMOrganization]?, _ error: AppError?) -> Void in  ... }

完成句柄需要具体类型,并且您已在 RLMOrganization 类的上下文中定义了 T = RLMOrganization

编辑:闭包不能是通用的,但函数可以:

func listCompletion<T: Decodable>(list: [T]?, error: AppError?) {
// you must cast `list` to a concrete type
}

func syncOrganizations() {
organizationsDAL.getList(sinceSyncToken: organizationsDAL.getLastSyncToken(), completion: listCompletion)
}

func syncProjects() {
projectsDAL.getList(sinceSyncToken: projectsDAL.getLastSyncToken(), completion: listCompletion)
}

func syncLocations() {
locationsDAL.getList(sinceSyncToken: locationsDAL.getLastSyncToken(), completion: listCompletion)
}

关于swift - 如何创建一个通用的完成闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52470664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com