Created
July 8, 2020 08:24
-
-
Save rehannali/11f787f2312aa6c3c6ce840f33bd4423 to your computer and use it in GitHub Desktop.
A simple solution for [weak self] or [unowned self] dance. No need to worry about retain cycles.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Delegation<Input, Output> { | |
private(set) var callback: ((Input) -> Output?)? | |
mutating func delegate<Target: AnyObject>(to target: Target, _ callback: @escaping (Target, Input) -> Output) { | |
self.callback = { [weak target] (input) in | |
guard let target = target else { | |
return nil | |
} | |
return callback(target, input) | |
} | |
} | |
func call(_ input: Input) -> Output? { | |
return self.callback?(input) | |
} | |
var isDelegateSet: Bool { | |
return callback != nil | |
} | |
} | |
extension Delegation { | |
mutating func removeDelegate() { | |
callback = nil | |
} | |
mutating func manuallyDelegate(with callback: @escaping (Input) -> Output) { | |
self.callback = callback | |
} | |
mutating func strongDelegate<Target: AnyObject>(to target: Target, _ callback: @escaping (Target, Input) -> Output) { | |
self.callback = { 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.callback?(input) | |
} | |
} | |
extension Delegation where Input == Void, Output == Void { | |
func call() { | |
return self.call(()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment