Skip to content

Instantly share code, notes, and snippets.

@tornikegomareli
Created March 6, 2023 08:46
Show Gist options
  • Save tornikegomareli/224e8a963b832528401be0e5f64abecf to your computer and use it in GitHub Desktop.
Save tornikegomareli/224e8a963b832528401be0e5f64abecf to your computer and use it in GitHub Desktop.
MultiCastDelegate
//
// MulticastDelegate.swift
//
//
// Created by Tornike on 12.12.22.
//
import Foundation
final class MulticastDelegate<T> {
private class DelegateWrapper {
weak var delegate: AnyObject?
init(_ delegate: AnyObject) {
self.delegate = delegate
}
}
// MARK: Instance Properties
private var delegateWrappers: [DelegateWrapper]
// swiftlint:disable force_cast
var delegates: [T] {
delegateWrappers = delegateWrappers.filter { $0.delegate != nil }
return delegateWrappers.map { $0.delegate! } as! [T]
}
init(delegates: [T] = []) {
delegateWrappers = delegates.map {
DelegateWrapper($0 as AnyObject)
}
}
// MARK: - Delegate Management
func addDelegate(_ delegate: T) {
let wrapper = DelegateWrapper(delegate as AnyObject)
delegateWrappers.append(wrapper)
}
func removeDelegate(_ delegate: T) {
guard let index = delegateWrappers.firstIndex(where: { $0.delegate === (delegate as AnyObject) }) else {
return
}
delegateWrappers.remove(at: index)
}
func invokeDelegates(_ closure: (T) -> Void) {
delegates.forEach { closure($0) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment