我目前正在学习如何实现通用功能。我正在尝试创建一个函数,该函数将返回具有通用类型的回调
这是我的代码
static func performPOST<T: DomainEntity>(action: Module, completion: @escaping (CallbackResponse, DomainObjectWrapper<T>?) -> Void) {
//logic implementation at first
switch action {
case .getMenuItem:
self.alamofireManager.request(urlRequest, encoding: URLEncoding.default, headers: headers).responseObject { (response: DataResponse<DomainObjectWrapper<MenuItemDO>>) in
var validateRequestResponse = RestHelper.validateRequestResponse(response: response)
let responseObject = validateRequestResponse.responseObject
if validateRequestResponse.isSuccess {}
else {
if let errorMessage = responseObject?.error {
validateRequestResponse.message = errorMessage
}
else if let warningMessage = responseObject?.warning {
validateRequestResponse.message = warningMessage
}
}
callbackResponse = RestHelper.bindValidateRequestResponse(validateRequestResponse: validateRequestResponse)
completion(callbackResponse, responseObject)
}
case .makeSales: break
case .attendance: break
}
}
我从Xcode收到此错误。它不会让我编译。
completion(callbackResponse, responseObject) <<-- This Line
Cannot convert value of type 'DomainObjectWrapper<MenuItemDO>?' to expected argument type 'DomainObjectWrapper<_>?'
这是我的其他课程
public class DomainObjectWrapper<T: Mappable>: Mappable {
public var data = [T]()
}
public class DomainEntity: Mappable {
public var id = UUID().uuidString
public var isDeleted = false
}
public class MenuItemDO: DomainEntity {
public var categoryId: String?
public var categoryName: String?
}
有人能指导我我所缺少的吗?
谢谢
答案 0 :(得分:0)
最近我为泛型参数函数做了一个不错的解决方案。这是命令模式的示例。这样你就可以使用这种模式接收带有泛型参数的回调。
protocol ParameterCommand {
func execute(with parameter: Any)
}
protocol CallbackCommand: ParameterCommand {
associatedtype CallBackParameterType
func execute(with callback: @escaping (CallBackParameterType) -> Void)
}
extension CallbackCommand {
func execute(with parameter: Any) {
if let parameter = parameter as? (CallBackParameterType) -> Void {
execute(with: parameter)
}
}
}