Skip to content

Instantly share code, notes, and snippets.

@kylehughes
Created May 15, 2025 22:33
Show Gist options
  • Save kylehughes/acd1e3dd632a3bd218c335caff3952bd to your computer and use it in GitHub Desktop.
Save kylehughes/acd1e3dd632a3bd218c335caff3952bd to your computer and use it in GitHub Desktop.
Function to weakify an instance function for safer passage to closures that would otherwise create a retain cycle.
@inlinable
public func weakify<Target, Output, each Argument>(
_ closureProvider: @escaping (Target) -> (repeat each Argument) -> Output,
on target: Target,
default: @autoclosure @escaping () -> Output
) -> (repeat each Argument) -> Output where Target: AnyObject {
{ [weak target] (arguments: repeat each Argument) in
guard let target else {
return `default`()
}
return closureProvider(target)(repeat each arguments)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment