Last active
December 23, 2022 07:21
-
-
Save onevcat/3c8f7c4e8c96f288854688cf34111636 to your computer and use it in GitHub Desktop.
An auto-weak delegate for handle modern delegate pattern.
This file contains hidden or 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
| public class Delegate<Input, Output> { | |
| public init() {} | |
| private var block: ((Input) -> Output?)? | |
| public 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) | |
| } | |
| } | |
| public func call(_ input: Input) -> Output? { | |
| return block?(input) | |
| } | |
| } | |
| public 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