Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping autoclosure captures 'inout' parameter 'self'

Tags:

swift

I've been writing a simplified version of Stack using enum types:

public enum Stack<Element> {
  case empty
  indirect case node(value: Element, next: Stack<Element>)

  public init(_ elements: Element...) {
    self = .empty
    elements.reversed().forEach(push)
  }

  public mutating func push(element: Element) {
    self = .node(value: element, next: self)
  }
}

However, I received the error below inside init and couldn't figure out why since self is a value type and forEach's body is not an escaping closure:

Escaping autoclosure captures 'inout' parameter 'self'

When I explicitly write the method inside the body, the error in question is gone.

elements.reversed().forEach { push(element: $0) }
like image 370
Ozgur Vatansever Avatar asked Oct 17 '25 07:10

Ozgur Vatansever


1 Answers

This is actually the same as the infamous "closure cannot implicitly capture a mutating self parameter" error in another guise. It is a consequence of the fact that push is mutating.

It is easy to confirm this by substituting a fake example:

public init(_ elements: Element...) {
    self = .empty
    elements.reversed().forEach(push)
}

public func push(element: Element) {
}

The only difference is that we took away the keyword mutating.

like image 108
matt Avatar answered Oct 19 '25 13:10

matt