john doe
john doe

Reputation: 9660

Escaping Closure captures non-escaping parameter dispatch

I am getting the error: Escaping closure captures non-escaping parameter dispatch. This error is coming on MovieService().getMovies line.

typealias ActionCreator = (_ dispatch: (Action) -> (), _ getState: () -> AppState) -> ()

func fetchMovies() -> ActionCreator   {
    
    return { dispatch, getState in
        
        MovieService.getMovies(url: "http://www.omdbapi.com/?s=Batman&page=2&apikey=YOURKEY") { result in
            
            switch result {
            case .success(let movies):
                if let movies = movies {
                    dispatch(.populateMovies(movies))
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
            
        }
    }
    
}

Any ideas?

Upvotes: 3

Views: 1109

Answers (1)

gcharita
gcharita

Reputation: 8327

As closures documentation states:

A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.

By default a closure is nonescaping like your dispatch parameter, but you are calling it inside an escaping closure which probably is the closure that you pass as a parameter in getMovies function.

The solution is simple, just add @escaping before the dispatch parameter type:

typealias ActionCreator = (_ dispatch: @escaping (Action) -> (), _ getState: () -> AppState) -> ()

Upvotes: 4

Related Questions