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) }
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With