Mutating a property of struct from inside a closure

895 Views Asked by At

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

There are 1 best solutions below

0
AMIT On BEST ANSWER

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)