Skip to content

chenmingbiao/SwiftMulticastDelegate

Repository files navigation

SwiftMulticastDelegate

English | 中文版

Build Status Swift 6.0+ iOS 12+ License platforms

Implementing multi cast of delegate in Swift. Fully compatible with Swift 6 Strict Concurrency.

Installation

1. Manual:

Copy SwiftMulticastDelegate.swift to your project

2. CocoaPods:

pod 'SwiftMulticastDelegate', :git => 'https://github.com/chenmingbiao/SwiftMulticastDelegate.git'

3. Swift Package Manager:

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") ]

Usage

Import the module

import SwiftMulticastDelegate
  1. Add to your class: let delegate = SwiftMulticastDelegate<MyProtocol>()
  2. Other classes must add as a delegate: obj.delegate.add(self)
  3. When you need to notify your delegates: multicastDelegate.invoke { delegate in delegate.func() }

Alternative version:

  1. Add to your class: let delegate = SwiftMulticastDelegate<MyProtocol>()
  2. Other classes must add as a delegate: obj.delegate += self
  3. When you need to notify your delegates: multicastDelegate => { $0.func() }

Example

// 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 -= viewModel1

Operators

Simplify multicast usage

+= calls add(_ delegate: T) or add(_ delegate: [T])

-= calls remove(_ delegate: T) or remove(_ delegate: [T])

=> calls invoke(_ invocation: (T) -> ())

License

SwiftMulticastDelegate is available under the MIT license.

About

Implementing multi cast of delegate in Swift.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors