在Swift 3.0中转义self(struct / enum)内部转义 [英] Mutating self (struct/enum) inside escaping closure in Swift 3.0

查看:162
本文介绍了在Swift 3.0中转义self(struct / enum)内部转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在swift 2.2中,当它在一个变异函数中时,我们可以在一个闭包中变异一个struct或enum。但在swift 3.0中它不再可能。我收到以下错误

In swift 2.2, We could mutate a struct or enum within a closure, when it was inside a mutating function. But in swift 3.0 its no longer possible. I get the following error


闭包不能隐式捕获变异的自我参数

closure cannot implicitly captured a mutating self parameter

这是一段代码片段,

struct Point {
    var x = 0.0, y = 0.0

    mutating func moveBy(x deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY

        test { (a) -> Void in
            // Get the Error in the below line.
            self.x = Double(a)
        }

    }

    mutating func test(myClosure: @escaping (_ a: Double) -> Void) {
        myClosure(3)
    }
}

我得到的值类型不应该是可变的。我有一些情况,当我收到API响应时,我必须在其中一个函数中修改结构中的一个变量。 (在完成结束时)

I get that value types are not supposed to be mutable. I have cases, where I do have to modify one variable in the struct within one of the functions, when I receive the API response. (In the completion closure)

我在swift 2.2中做了什么,不可能或者有没有办法实现这个目标?

Is what I was doing in swift 2.2, impossible or is there way to accomplish this?

推荐答案

问题是 @escaping闭包可以存储以供以后执行


逃离关闭

当闭包作为参数传递给函数时,闭包被称为转义函数,但在函数返回后调用。 ...

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. ...

闭包可以转义的一种方法是存储在函数外部定义的变量....

One way that a closure can escape is by being stored in a variable that is defined outside the function....

由于闭包可以存储并存在于函数范围之外,因此闭包内的struct / enum(self)将被复制(它是一个值)闭包的参数。并且,如果它被允许变异,那么关闭可能会有一个旧的副本,导致不必要的结果。

Since the closure can be stored and live outside the scope of the function, the struct/enum inside the closure (self) will be copied (it is a value) as a parameter of the closure. And, if it was allowed to mutate, the closure could have an old copy of it, causing unwanted results.

所以,回答你的问题,你不能;除非你能删除@escaping(不是你的情况,因为它是第三方API)

So, in answer to your question, you cannot; unless you are able to remove "@escaping" (not your case because it's a 3rd party API)

这篇关于在Swift 3.0中转义self(struct / enum)内部转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆