2

So I have my first closure here:

var instructions: (() -> Void) = {
    print("First")
}

instructions() /// prints "First"

Now I have another closure:

let additionalInstructions: (() -> Void) = {
    print("Second")
}

additionalInstructions() /// prints "Second"

I want to "append" additionalInstructions to the end of instructions... is this possible? I tried making a new closure containing both of them, like this:

let finalInstructions: (() -> Void) = {
    instructions()
    additionalInstructions()
}

finalInstructions()

This prints

First

Second

But, when I replace instructions with finalInstructions, I get an EXC_BAD_ACCESS.

instructions = finalInstructions
instructions() /// error here

EXC_BAD_ACCESS error

I think this is because closures are reference types, and some sort of loop happens when instructions contains itself. Is there a way to avoid the error? Making a new closure like finalInstructions, just as a container, also seems kind of clunky.

3
  • 1
    Is there some relationship or dependency between instructions and additionalInstructions? Right now it only looks like two random closures you want to be executed after each other. Like you could make an array of them instead of creating a third closure, [instructions, additionalInstructions] Commented Dec 21, 2020 at 21:58
  • No, they have no relation with each other. An array sounds good, so I would use forEach or something?
    – aheze
    Commented Dec 21, 2020 at 22:02
  • 1
    Yes, something like that. Commented Dec 21, 2020 at 22:03

2 Answers 2

3

This is some interesting semantics I didn't expect, but what you're seeing is an infinite recursion, which crashes due to a stack overflow. You can confirm this by running this code in a project, where the debugger will catch the error. You'll see thousands of stackframes of the same closure being called.

It appears that the reference to instructions within your closure is capturing its new, self-referential value, rather than its previous value.

Your approach of using a new variable like finalInstructions is much better. Not only because it avoids this issue, but also because it's much more readable code.

Here's a simpler, more minimal demonstration of the problem:

var closure = { print("initial definition") }

closure() // prints "initial definition"

closure = {
    print("second definition")
    closure()
}

closure() // prints "second definition" repeatedly, until the stack overflows

FYI, I asked about this on the Swift forums: https://forums.swift.org/t/mutable-closures-can-capture-themselves/43228

1
  • Nice, due to a "stack overflow"? Thanks for the insight!
    – aheze
    Commented Dec 21, 2020 at 22:03
2

It's easy to put them together. It's not easy to take them apart, like C#'s delegates are.

To do that, you'll need to maintain a bunch of junk like below. Better to use Combine, these days.

final class MultiClosureTestCase: XCTestCase {
  func test_multiClosure() {
    var x = 0
    let closures: [EquatableClosure<()>] = [
      .init { _ in x += 1 },
      .init { _ in x += 2 }
    ]
    let multiClosure = MultiClosure(closures)
    multiClosure()
    XCTAssertEqual(x, 3)
    multiClosure -= closures.first!
    multiClosure()
    XCTAssertEqual(x, 5)
  }
   
  func test_setRemoval() {
    let closure: EquatableClosure<()>! = .init { _ in }
    let multiClosure = MultiClosure(closure)
    
    XCTAssertNotEqual(multiClosure.closures, [])
    XCTAssertNotEqual(closure.multiClosures, [])
    multiClosure -= closure
    XCTAssertEqual(multiClosure.closures, [])
    XCTAssertEqual(closure.multiClosures, [])
  }

  func test_deallocation() {
    var closure: EquatableClosure<()>! = .init { _ in }
    var multiClosure: MultiClosure! = .init(closure)

    XCTAssertNotEqual(multiClosure.closures, [])
    closure = nil
    XCTAssertEqual(multiClosure.closures, [])

    closure = EquatableClosure { _ in }
    multiClosure += closure
    XCTAssertNotEqual(closure.multiClosures, [])
    multiClosure = nil
    XCTAssertEqual(closure.multiClosures, [])
  }
}
/// Use this until Swift has unowned-referencing collections.
public final class UnownedReferencer<Reference: AnyObject>: HashableViaID {
  public init(_ reference: Reference) {
    self.reference = reference
  }

  public unowned let reference: Reference
}

/// Use this until Swift has weak-referencing collections.
public final class WeakReferencer<Reference: AnyObject>: HashableViaID {
  public init(_ reference: Reference) {
    self.reference = reference
  }

  public weak var reference: Reference?
}

/// Remove the first `UnownedReferencer` with this `reference`
public func -= <Reference: Equatable>(
  set: inout Set< UnownedReferencer<Reference> >,
  reference: Reference
) {
  guard let referencer = ( set.first { $0.reference == reference} )
  else { return }

  set.remove(referencer)
}

/// Remove the first `WeakReferencer` with this `reference`
public func -= <Reference: Equatable>(
  set: inout Set< WeakReferencer<Reference> >,
  reference: Reference
) {
  guard let referencer = ( set.first { $0.reference == reference } )
  else { return }

  set.remove(referencer)
}
/// A workaround for Swift not providing a way to remove closures
/// from a collection of closures.
///- Note: Designed for one-to-many events, hence no return value.
///  Returning a single value from multiple closures doesn't make sense.
public final class MultiClosure<Input>: Equatable {
  public init(_ closures: EquatableClosure<Input>...) {
    self += closures
  }

  public init<Closures: Sequence>(_ closures: Closures)
  where Closures.Element == EquatableClosure<Input> {
    self += closures
  }

  var closures: Set<
    UnownedReferencer< EquatableClosure<Input> >
  > = []

// MARK: deallocation
  // We can't find self in `closures` without this.
  fileprivate lazy var unownedSelf = UnownedReferencer(self)

  // Even though this MultiClosure will be deallocated,
  // its corresponding WeakReferencers won't be,
  // unless we take this manual action or similar.
  deinit {
    for closure in closures {
      closure.reference.multiClosures.remove(unownedSelf)
    }
  }
}

public extension MultiClosure {
  /// Execute every closure
  func callAsFunction(_ input: Input) {
    for closure in closures {
      closure.reference(input)
    }
  }
}

public extension MultiClosure where Input == () {
  /// Execute every closure
  func callAsFunction() {
    self(())
  }
}

/// A wrapper around a closure, for use with MultiClosures
public final class EquatableClosure<Input>: Equatable {
  public init(_ closure: @escaping (Input) -> Void) {
    self.closure = closure
  }

  /// Execute the closure
  func callAsFunction(_ input: Input) {
    closure(input)
  }

  private let closure: (Input) -> Void

// MARK: deallocation
  var multiClosures: Set<
    UnownedReferencer< MultiClosure<Input> >
  > = []

  // We can't find self in `multiClosures` without this.
  fileprivate lazy var unownedSelf = UnownedReferencer(self)

  deinit {
    for multiClosure in multiClosures {
      multiClosure.reference.closures.remove(unownedSelf)
    }
  }
}

/// Add `closure` to the set of closures that runs
/// when `multiClosure` does
public func += <Input>(
  multiClosure: MultiClosure<Input>,
  closure: EquatableClosure<Input>
) {
  multiClosure.closures.formUnion([closure.unownedSelf])
  closure.multiClosures.formUnion([multiClosure.unownedSelf])
}

/// Add `closures` to the set of closures that runs
/// when `multiClosure` does
public func += <
  Input,
  Closures: Sequence
>(
  multiClosure: MultiClosure<Input>,
  closures: Closures
)
where Closures.Element == EquatableClosure<Input> {
  for closure in closures {
    multiClosure += closure
  }
}

/// Remove `closure` from the set of closures that runs
/// when `multiClosure` does
public func -= <Input>(
  multiClosure: MultiClosure<Input>,
  closure: EquatableClosure<Input>
) {
  multiClosure.closures.remove(closure.unownedSelf)
  closure.multiClosures.remove(multiClosure.unownedSelf)
}
/// An `Identifiable` instance that uses its `id` for equality and hashability.
public protocol HashableViaID: Hashable, Identifiable { }

// MARK: - Equatable
public extension HashableViaID {
  static func == (equatable0: Self, equatable1: Self) -> Bool {
    equatable0.id == equatable1.id
  }
}

// MARK: - Hashable
public extension HashableViaID {
  func hash(into hasher: inout Hasher) {
    hasher.combine(id)
  }
}
// MARK: - AnyObject
public extension Equatable where Self: AnyObject {
  static func == (class0: Self, class1: Self) -> Bool {
    class0 === class1
  }
}
1
  • That's a lot of code. I'll probably just go with a second closure for now...
    – aheze
    Commented Dec 22, 2020 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.