0

我正在尝试在结构中的变异函数中编写闭包,并从闭包内部更改结构的一个属性。但它给了我如下错误:

“转义闭包捕获变异的‘自我’参数”

struct Sample {
  var a = "Jonh Doe"

  mutating func sample() {
    let closure = { () in
      self.a = "eod hnoj"
    }
    print(closure)
    print(a)
  }
}

var b = Sample()
b.sample()
4

1 回答 1

0

试试下面的示例代码。

struct Sample {
  var a = "Jonh Doe"

  mutating func sample() {
    let closure = {
        Sample(a: "eod hnoj")
    }
    self = closure()
  }
}

var b = Sample()
b.sample()
print(b)
于 2020-03-02T14:05:59.703 回答