0

I am trying to write closure inside mutating function in struct and changing one property of struct from inside closure. But it is giving me error as below:

"Escaping closure captures mutating 'self' parameter "

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()
nikksindia
  • 1,147
  • 1
  • 10
  • 18
  • Unlike classes (whose objects exist in one place, and whose memory address gives them a stable identity), structs are copied on every passing into a funciton, assignment to a variable, etc. If this *was* allowed, which of those many copies would you expect to be mutated? – Alexander Mar 02 '20 at 13:55

1 Answers1

0

Try this example code below.

struct Sample {
  var a = "Jonh Doe"

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

var b = Sample()
b.sample()
print(b)
AMIT
  • 906
  • 1
  • 8
  • 20