Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Delegation.swift
- // Oneload
- //
- // Created by Rehan Ali on 22/03/2019.
- // Copyright © 2019 OneLoad. All rights reserved.
- //
- import Foundation
- struct Delegation<Input, Output> {
- private(set) var completionBlock: ((Input) -> Output?)?
- mutating func delegate<Target: AnyObject>(to target: Target,_ completion: @escaping (Target, Input) -> Output) {
- self.completionBlock = { [weak target] (input) in
- guard let target = target else {
- return nil
- }
- return completion(target, input)
- }
- }
- func call(_ input: Input) -> Output? {
- return self.completionBlock?(input)
- }
- var isDelegateSet: Bool {
- return completionBlock != nil
- }
- }
- extension Delegation {
- mutating func removeDelegate() {
- completionBlock = nil
- }
- mutating func manuallyDelegate(with callback: @escaping (Input) -> Output) {
- self.completionBlock = callback
- }
- mutating func strongDelegate<Target: AnyObject>(to target: Target,_ callback: @escaping (Target, Input) -> Output) {
- self.completionBlock = { input in
- return callback(target, input)
- }
- }
- }
- extension Delegation where Input == Void {
- func call() -> Output? {
- return self.call(())
- }
- }
- extension Delegation where Output == Void {
- func call(_ input: Input) {
- self.completionBlock?(input)
- }
- }
- extension Delegation where Input == Void, Output == Void {
- func call() {
- return self.call(())
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement