Skip to content

Instantly share code, notes, and snippets.

@vincent-pradeilles
Created January 2, 2021 17:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vincent-pradeilles/86b32d3341aa47bcf6ae46d8d726f2f7 to your computer and use it in GitHub Desktop.
Save vincent-pradeilles/86b32d3341aa47bcf6ae46d8d726f2f7 to your computer and use it in GitHub Desktop.
import UIKit
class Service {
func call(with completion: @escaping (Int) -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
completion(42)
}
}
}
class ViewController: UIViewController {
let service = Service()
let label = UILabel()
func format(data: Int) -> String {
return "\(data)"
}
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Retrieved data: "
service.call(with: weakify { strongSelf, data in
/* Specific logic */
let formatted = strongSelf.format(data: data)
strongSelf.label.text?.append(formatted)
/* End of specific logic */
})
}
}
protocol Weakifiable: class { }
extension NSObject: Weakifiable { }
extension Weakifiable {
func weakify<T>(_ code: @escaping (Self, T) -> Void) -> (T) -> Void {
return {
/* Begin boilerplate */
[weak self] (data) in
guard let self = self else { return }
/* End boilerplate */
code(self, data)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment