Skip to content

Instantly share code, notes, and snippets.

@SergLam
Created November 4, 2021 22:16
Show Gist options
  • Save SergLam/de4ffd8aab81484998570746a6e30869 to your computer and use it in GitHub Desktop.
Save SergLam/de4ffd8aab81484998570746a6e30869 to your computer and use it in GitHub Desktop.
Multicast Delegate - wrapper class to implement one to many delegate with Array of optionals wrapper
import Foundation
// https://betterprogramming.pub/implement-a-multicast-delegate-design-pattern-in-swift-5-72079d695cfe
public class MulticastDelegate<T> {
// 1
private class Wrapper {
weak var delegate: AnyObject?
init(_ delegate: AnyObject) {
self.delegate = delegate
}
}
// 2
private var wrappers: [Wrapper] = []
public var delegates: [T] {
return wrappers
.compactMap{ $0.delegate } as! [T]
}
// 3
public func add(delegate: T) {
let wrapper = Wrapper(delegate as AnyObject)
wrappers.append(wrapper)
}
// 4
public func remove(delegate: T) {
guard let index = wrappers.firstIndex(where: {
$0.delegate === (delegate as AnyObject)
}) else {
return
}
wrappers.remove(at: index)
}
// 5
public func invokeForEachDelegate(_ handler: (T) -> ()) {
delegates.forEach { handler($0) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment