Last active
September 9, 2018 20:33
-
-
Save Sajjon/1976f6f754d6239515c71b262a081be1 to your computer and use it in GitHub Desktop.
Weakify / Unownify Methods
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
| typealias NoArgMethod<StrongObject, ReturnType> = (StrongObject) -> () -> ReturnType | |
| typealias SingleArgumentMethod<Argument, StrongObject> = (StrongObject) -> (Argument) -> Void | |
| func unown<O, R>( | |
| _ object: O, // This is strong | |
| _ method: @escaping NoArgMethod<O, R> | |
| ) -> () -> R where O: AnyObject, R: Any | |
| { | |
| return { [unowned object] in | |
| method(object)() | |
| } | |
| } | |
| func weakify<O, A>( | |
| _ object: O, // This is strong | |
| _ method: @escaping SingleArgumentMethod<A, O> | |
| ) -> (A) -> Void where O: AnyObject, A: Any | |
| { | |
| return { [weak object] (argument: A) in | |
| guard let strongObject = object else { return } | |
| method(strongObject)(argument) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment