Skip to content

Instantly share code, notes, and snippets.

@azonov
Created September 12, 2019 10:03
Show Gist options
  • Save azonov/96c8a54cae75e14f21ec5c2a37f5e22f to your computer and use it in GitHub Desktop.
Save azonov/96c8a54cae75e14f21ec5c2a37f5e22f to your computer and use it in GitHub Desktop.
Weak self capturing in Swift closures
func weak<T: AnyObject>(_ obj: T, _ block: @escaping (T) -> () -> Void) -> () -> Void {
return { [weak obj] in
obj.map(block)?()
}
}
func weak<T: AnyObject, Argument>(_ obj: T, _ block: @escaping (T) -> (Argument) -> Void) -> (Argument) -> Void {
return { [weak obj] a in
obj.map(block)?(a)
}
}
@azonov
Copy link
Author

azonov commented Sep 12, 2019

// Usage

// Without weak

let doneHandler: () -> Void = { [weak self] in
    self?.deleteSmth()
}
let alertModel = AlertViewModel(message: "Delete something?",  doneHandler: doneHandler)
```​

// Using weak
`let alertModel = AlertViewModel(message: message: "Delete something?",  doneHandler: weak(self, ViewModel.deleteSomething)`

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