Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Swift 3中为闭包内的inout参数赋值_Swift_Closures_Completionhandler_Inout - Fatal编程技术网

在Swift 3中为闭包内的inout参数赋值

在Swift 3中为闭包内的inout参数赋值,swift,closures,completionhandler,inout,Swift,Closures,Completionhandler,Inout,在完成块内尝试为函数参数赋值时出现错误,错误为“转义闭包只能通过值显式捕获inout参数” 我怎样才能解决这个问题?任何提示都非常感谢 func fetchCurrentUser(user: inout User? ) { self.fetchUser(withId: AuthProvider.sharedInstance.currentUserId(), completionHandler: { fetchedUser in guard let newU

在完成块内尝试为函数参数赋值时出现错误,错误为“转义闭包只能通过值显式捕获inout参数”

我怎样才能解决这个问题?任何提示都非常感谢

func fetchCurrentUser(user: inout User? ) {
    self.fetchUser(withId: AuthProvider.sharedInstance.currentUserId(), completionHandler: {
        fetchedUser in
        guard let newUser = fetchedUser else { return }
        user = newUser // error Here
    })
}

这将不起作用,因为您使用的是完成处理程序。
self.fetchUser
将(几乎)立即返回,并且每当后台工作(很可能是网络请求)完成时,将执行完成处理程序

函数
fetchCurrentUser
调用
self.fetchUser
并返回,因此它将在执行完成块之前返回

不能在转义闭包上使用inout参数(错误消息也会告诉您这一点)。转义闭包是在传递它的函数返回后执行的闭包


您可以重写函数以同时使用完成处理程序,也可以将函数更改为在结束fetchCurrentUser函数之前等待完成处理程序运行。但是对于第二种方法,请注意,这也会阻止函数调用方执行任何其他操作。

我建议进行以下重构:

func fetchCurrentUser(callback: @escaping (User) -> ()) {
    self.fetchUser(withId: AuthProvider.sharedInstance.currentUserId(), completionHandler: {
        fetchedUser in
        guard let newUser = fetchedUser else { return }
        callback(newUser)
    })
}

或者,如果您希望fetchCurrentUser是同步的,您可以使用信号量

谢谢您的见解。我计算了访问fetchedUser的时间,然后会为inout参数(用户)分配该值。您可能会发现这很有帮助。演示如何在转义闭包中修改引用传递变量。我建议将闭包参数设置为可选参数,例如
func fetchCurrentUser(回调:@escaping(User?->Void){…}
,失败时,使用
nil
调用闭包。你真的想让打电话的人知道是否有错误。这是一个同步的建议,几乎总是一个坏主意,通常代码会嗅到根深蒂固的设计缺陷。