Search code examples
iosswiftswift3completionhandler

Passing a completion handler nested into another class


I am working on a library where using Swift. I would like to know is there any better approach I can use in the below scenario,

ViewController.swift

Movie.searchMovie(name: “AVENGERS”, completionHandler: (Result<[MovieInfo],Error>))

The above controller is from sample application where I invoke a public method in Movie Library.

Movie.swift

public class Movie: NSObject {
        public class func searchMovie(name: String, completionHandler: (Result<[MovieInfo],Error>)) {
          Records.sharedInstance.searchMovieWithName(name: name, completionBlock: { (data, error) in
            guard data != nil  else {
                completionBlock(Result.failure(error ?? “ERROR” as! Error))
            }
            guard let list = data as? [Item] else {
                completionBlock(Result.failure(error ?? "ERROR" as! Error))
            }
            completionBlock(Result.success(list))
        })
        }
}

and

Records.swift

func searchMovieWithName(name: String, completionHandler: (Result<[MovieInfo],Error>)) {
    //Implementation to search
}

Is this how its done? Is there anyway I can do better with completion handlers?


Solution

  • The problem is your completionHandler is not a completion handler:

    public class func searchMovie(
        name: String, completionHandler: (Result<[MovieInfo],Error>))
    

    It is merely a Result object. A handler is a function:

    public class func searchMovie(
        name: String, completionHandler: (Result<[MovieInfo],Error>) -> Void)
    

    Now you have a completion handler that you can call with a Result parameter.