// // Delegation.swift // Oneload // // Created by Rehan Ali on 22/03/2019. // Copyright © 2019 OneLoad. All rights reserved. // import Foundation struct Delegation { private(set) var completionBlock: ((Input) -> Output?)? mutating func delegate(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(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(()) } }