gpt4 book ai didi

swift - 转义闭包捕获非转义参数派发

转载 作者:行者123 更新时间:2023-12-05 02:50:01 25 4
gpt4 key购买 nike

我收到错误:转义闭包捕获非转义参数分派(dispatch)。此错误出现在 MovieService().getMovies 行。

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)
}

}
}

}

有什么想法吗?

最佳答案

作为closures文档状态:

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

默认情况下,闭包是 nonescaping 就像你的 dispatch 参数,但你在 escaping 闭包中调用它,这可能是闭包您在 getMovies 函数中作为参数传递。

解决方法很简单,在dispatch参数类型前加上@escaping即可:

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

关于swift - 转义闭包捕获非转义参数派发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63783349/

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