Created
May 15, 2025 22:33
-
-
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.
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
@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