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 got stuck receiving the below error at initializer 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) }
Can you help me understand why?