Created
May 7, 2019 03:26
-
-
Save iOSleep/6e352cc429dbca741f25b49c12ba9e4e to your computer and use it in GitHub Desktop.
An auto-weak delegate for handle modern delegate pattern.
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
class Delegate<Input, Output> { | |
private var block: ((Input) -> Output?)? | |
func delegate<T: AnyObject>(on target: T, block: ((T, Input) -> Output)?) { | |
self.block = { [weak target] input in | |
guard let target = target else { return nil } | |
return block?(target, input) | |
} | |
} | |
func call(_ input: Input) -> Output? { | |
return block?(input) | |
} | |
} | |
extension Delegate where Input == Void { | |
func call() -> Output? { | |
return call(()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment