【问题标题】:Mutating a property of struct from inside a closure [duplicate]从闭包内部改变结构的属性[重复]
【发布时间】:2023-03-05 01:31:01
【问题描述】:

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

“转义闭包捕获变异的'self'参数”

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

【问题讨论】:

  • 与类不同(其对象存在于一个位置,并且其内存地址为它们提供了一个稳定的标识),结构在每次传递到函数时被复制,分配给变量等。如果这 允许的,你希望在这么多副本中的哪一个被变异?

标签: swift struct value-type mutating-function


【解决方案1】:

试试下面的示例代码。

struct Sample {
  var a = "Jonh Doe"

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 2018-10-29
    相关资源
    最近更新 更多