Created
November 4, 2021 22:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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