转义闭包捕获非转义参数“函数” Xcode 说
Posted
技术标签:
【中文标题】转义闭包捕获非转义参数“函数” Xcode 说【英文标题】:Escaping closure captures non-escaping parameter 'function' Xcode says 【发布时间】:2021-12-23 14:49:33 【问题描述】:我正在尝试在两个 API 请求完成后执行 segue,并且我拥有所需的所有数据。我正在尝试这样做,因为请求需要一些时间。但是,当我尝试执行类似 post 的操作时,出现以下错误:
1. Passing a non-escaping function parameter 'anotherFunc' to a call to a non-escaping function parameter can allow re-entrant modification of a variable
2. Escaping closure captures non-escaping parameter 'anotherFunc'
3. Escaping closure captures non-escaping parameter 'function'
我在出现错误的地方添加了 cmets。这是我的代码:
func getUsernameRequest(function: () -> Void)
// send an API request to get the userinfo
let url = "\(K.API.baseAPIEndpoint)/user"
let headers: HTTPHeaders = [...]
AF.request(url, headers: headers).responseDecodable(of: UserModel.self) response in // this is where the #3 error shows up
if let value = response.value
self.username = value.username
// and do other things
function()
else
offlineBanner()
func getMessagesRequest(function: (()->Void)->Void, anotherFunc:()->Void)
let postDetailUrl = "\(K.API.baseAPIEndpoint)/posts/\(postArray[indexPath.row].id)"
let headers: HTTPHeaders = [...]
// send an API request to get all the associated messages
AF.request(postDetailUrl, headers: headers).responseDecodable(of: PostDetailModel.self) response in // this is the #2 error shows up
if let value = response.value
self.messages = value.messages
function(anotherFunc) // this is where the #1 error shows up
else
offlineBanner()
func performSegueToChat() -> Void
self.performSegue(withIdentifier: K.Segue.GotoChat, sender: self)
getMessagesRequest(function: getUsernameRequest, anotherFunc: performSegueToChat)
提前谢谢你。
【问题讨论】:
【参考方案1】:我用下面的代码做了这个,它按我的预期工作! (但它们不太干净)
func getUsernameRequest(function: @escaping() -> Void)
// send an API request to get the username
let url = "\(K.API.baseAPIEndpoint)/user"
AF.request(url, headers: headers).responseDecodable(of: GetUsernameModel.self) response in
if let value = response.value
self.username = value.username
function()
else
offlineBanner()
func getMessagesRequest(function: @escaping(@escaping()->Void)->Void, anotherFunc: @escaping()->Void)
let postDetailUrl = "\(K.API.baseAPIEndpoint)/posts/\(postArray[indexPath.row].id)"
// send an API request to get all the associated messages and put them into messages array
AF.request(postDetailUrl, headers: headers).responseDecodable(of: PostDetailModel.self) response in
if let value = response.value
self.messages = value.messages
function(anotherFunc)
else
offlineBanner()
func performSegueToChat() -> Void
self.performSegue(withIdentifier: K.Segue.GotoChat, sender: self)
getMessagesRequest(function: getUsernameRequest, anotherFunc: performSegueToChat)
【讨论】:
以上是关于转义闭包捕获非转义参数“函数” Xcode 说的主要内容,如果未能解决你的问题,请参考以下文章