Implementing multi cast of delegate in Swift. Fully compatible with Swift 6 Strict Concurrency.
Copy SwiftMulticastDelegate.swift to your project
pod 'SwiftMulticastDelegate', :git => 'https://github.com/chenmingbiao/SwiftMulticastDelegate.git'You can use Swift Package Manager and specify a dependency in Package.swift by adding this:
dependencies: [
.package(url: "https://github.com/chenmingbiao/SwiftMulticastDelegate.git", from: "1.0.0")
]
Import the module
import SwiftMulticastDelegate- Add to your class:
let delegate = SwiftMulticastDelegate<MyProtocol>() - Other classes must add as a delegate:
obj.delegate.add(self) - When you need to notify your delegates:
multicastDelegate.invoke { delegate in delegate.func() }
Alternative version:
- Add to your class:
let delegate = SwiftMulticastDelegate<MyProtocol>() - Other classes must add as a delegate:
obj.delegate += self - When you need to notify your delegates:
multicastDelegate => { $0.func() }
// MARK: - Delegate Protocol
protocol ServiceStateDelegate: AnyObject {
func didUpdateState(to state: String)
}
// MARK: - Service
class NetworkService {
var delegates = SwiftMulticastDelegate<ServiceStateDelegate>()
func changeState() {
// ... some logic ...
delegates => {
$0.didUpdateState(to: "Connected")
}
}
}
// MARK: - Observer
class ViewModel: ServiceStateDelegate {
func didUpdateState(to state: String) {
print("ViewModel received state: \(state)")
}
}
let service = NetworkService()
let viewModel1 = ViewModel()
let viewModel2 = ViewModel()
// Add delegates
service.delegates += viewModel1
service.delegates += viewModel2
// Trigger invocation
service.changeState()
// Remove delegates
service.delegates -= viewModel1Simplify multicast usage
+= calls add(_ delegate: T) or add(_ delegate: [T])
-= calls remove(_ delegate: T) or remove(_ delegate: [T])
=> calls invoke(_ invocation: (T) -> ())
SwiftMulticastDelegate is available under the MIT license.