Advertisement
rehannali

Closure based delegation swift

Apr 18th, 2019
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.58 KB | None | 0 0
  1. //
  2. //  Delegation.swift
  3. //  Oneload
  4. //
  5. //  Created by Rehan Ali on 22/03/2019.
  6. //  Copyright © 2019 OneLoad. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10.  
  11. struct Delegation<Input, Output> {
  12.     private(set) var completionBlock: ((Input) -> Output?)?
  13.    
  14.     mutating func delegate<Target: AnyObject>(to target: Target,_ completion: @escaping (Target, Input) -> Output) {
  15.         self.completionBlock = { [weak target] (input) in
  16.             guard let target = target else {
  17.                 return nil
  18.             }
  19.             return completion(target, input)
  20.         }
  21.     }
  22.    
  23.     func call(_ input: Input) -> Output? {
  24.         return self.completionBlock?(input)
  25.     }
  26.    
  27.     var isDelegateSet: Bool {
  28.         return completionBlock != nil
  29.     }
  30. }
  31.  
  32. extension Delegation {
  33.     mutating func removeDelegate() {
  34.         completionBlock = nil
  35.     }
  36.    
  37.     mutating func manuallyDelegate(with callback: @escaping (Input) -> Output) {
  38.         self.completionBlock = callback
  39.     }
  40.    
  41.     mutating func strongDelegate<Target: AnyObject>(to target: Target,_ callback: @escaping (Target, Input) -> Output) {
  42.         self.completionBlock = { input in
  43.             return callback(target, input)
  44.         }
  45.     }
  46. }
  47.  
  48. extension Delegation where Input == Void {
  49.     func call() -> Output? {
  50.         return self.call(())
  51.     }
  52. }
  53.  
  54. extension Delegation where Output == Void {
  55.     func call(_ input: Input) {
  56.         self.completionBlock?(input)
  57.     }
  58. }
  59.  
  60. extension Delegation where Input == Void, Output == Void {
  61.     func call() {
  62.         return self.call(())
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement