Last active
May 13, 2020 08:22
-
-
Save klundberg/bf591578ff41f8ad33b3 to your computer and use it in GitHub Desktop.
Weakify functions to help you weakly bind instances to static method references
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
// these functions take a swift class's statically referenced method and the instance those methods | |
// should apply to, and returns a function that weakly captures the instance so that you don't have | |
// to worry about memory retain cycles if you want to directly use an instance method as a handler | |
// for some object, like NSNotificationCenter. | |
// | |
// For more information, see this post: | |
// http://www.klundberg.com/blog/capturing-objects-weakly-in-instance-method-references-in-swift/ | |
func weakify <T: AnyObject, U>(owner: T, f: T->U->()) -> U -> () { | |
return { [weak owner] obj in | |
if let this = owner { | |
f(this)(obj) | |
} | |
} | |
} | |
func weakify <T: AnyObject>(owner: T, f: T->()->()) -> () -> () { | |
return { [weak owner] in | |
if let this = owner { | |
f(this)() | |
} | |
} | |
} | |
func weakify <T: AnyObject, U>(owner: T, f: T->()->U) -> () -> U? { | |
return { [weak owner] in | |
if let this = owner { | |
return f(this)() | |
} else { | |
return nil | |
} | |
} | |
} | |
func weakify <T: AnyObject, U, V>(owner: T, f: T->U?->()) -> V -> () { | |
return { [weak owner] obj in | |
if let this = owner { | |
f(this)(obj as? U) | |
} | |
} | |
} | |
func weakify <T: AnyObject, U, V>(owner: T, f: T->U->V) -> U -> V? { | |
return { [weak owner] obj in | |
if let this = owner { | |
return f(this)(obj) | |
} else { | |
return nil | |
} | |
} | |
} | |
func weakify <T: AnyObject, U>(owner: T, f: T->()->()) -> U -> () { | |
return { [weak owner] _ in | |
if let this = owner { | |
f(this)() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Similar versions of
unownify
can also be handy for cases when we know theowner
will definitely be around. Especially, in cases where the methods return a value (so that a non-optional value is returned instead of an optional value).