rehannali icon

Closure based delegation swift

rehannali | PRO | 04/18/19 11:35:16 AM UTC | 0 ⭐ | 571 👁️ | Never ⏰ | []
Swift |

1.58 KB

|

None

|

0 👍

/

0 👎

//
//  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(())
    }
}

Comments