Skip to content

Instantly share code, notes, and snippets.

@klundberg
Last active May 13, 2020 08:22
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klundberg/bf591578ff41f8ad33b3 to your computer and use it in GitHub Desktop.
Save klundberg/bf591578ff41f8ad33b3 to your computer and use it in GitHub Desktop.
Weakify functions to help you weakly bind instances to static method references
// 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)()
}
}
}
@priteshshah1983
Copy link

priteshshah1983 commented Dec 16, 2017

Similar versions of unownify can also be handy for cases when we know the owner 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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment