Search code examples
iosswiftmoya

Swift incorrect closure in function declaration


I am trying to use Moya Networking in my project. I am using this example. The example is making moya request to connect to server in view controller on Line 56 which is below and using callback methods in Line 72 and Line 78

func uploadGiphy() {
    provider.request(MultiTarget(Giphy.upload(gif: Giphy.animatedBirdData)),
                     callbackQueue: DispatchQueue.main,
                     progress: progressClosure,
                     completion: progressCompletionClosure)
}

I want to write this function in NetworkHelper.swift instead of my view controller but, use its two callback methods (Line 72 and Line 78) in my view controller.

So I wrote the function in NetworkHelper:

static func getUsers(amount:Int=2, 
gender:Gender = .Male, 
success successCallback: @escaping ([UserModelMain]) -> Void, 
error errorCallback: @escaping (Swift.Error) -> Void, 
failure failureCallback: @escaping (Moya.MoyaError) -> Void, 
progress progressClosure: @escaping (Moya.ProgressResponse) -> Void,
progressCompletion progressCompletionClosure:  @escaping (Moya.Completion) -> Void) 
{

     provider.request(.getUsers(amount: amount, gender: gender),
                         callbackQueue: DispatchQueue.main,
                         progress: progressClosure,
                         completion: progressCompletionClosure)
}

Its showing error:

Cannot convert value of type '((Result) -> Void) -> Void' to expected argument type 'Completion' (aka '(Result) -> ()')

I think I am writing my function getUsers wrong. I messed it up. I am weak at closures.

Kindly help.

Source Code of request function from Moya networking library:

/// Designated request-making method. 
Returns a `Cancellable` token to cancel the request later.
@discardableResult
open func request(_ target: Target,
                  callbackQueue: DispatchQueue? = .none,
                  progress: ProgressBlock? = .none,
                  completion: @escaping Completion) -> Cancellable {

let callbackQueue = callbackQueue ?? self.callbackQueue
return requestNormal(target, callbackQueue: callbackQueue, progress: progress, completion: completion)
}

Solution

  • Moya.Completion is already a completion block. You just need to pass Moya.Completion as an argument, instead of (Moya.Completion) -> Void.

    progressCompletion progressCompletionClosure: @escaping Moya.Completion)
    

    Your current code, like the error suggest, is sending ((Result) -> Void) -> Void