swiftstructvalue-typemutating-function

Mutating a property of struct from inside a closure


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

Solution

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