Skip to content

Instantly share code, notes, and snippets.

@hoc081098
Created April 10, 2020 07:26
Show Gist options
  • Save hoc081098/8e1395953fe6242d2910cbea8d001f0f to your computer and use it in GitHub Desktop.
Save hoc081098/8e1395953fe6242d2910cbea8d001f0f to your computer and use it in GitHub Desktop.
import UIKit
import PlaygroundSupport
protocol Weakifiable: AnyObject { }
extension NSObject: Weakifiable { }
extension Weakifiable {
func weakify(_ block: @escaping (Self) -> Void) -> () -> Void {
{ [weak self] in self.map(block) }
}
func weakify<T>(_ block: @escaping (Self, T) -> Void) -> (T) -> Void {
{ [weak self] in if let self = self { block(self, $0) } }
}
}
class MyVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
loadData(weakify { (strongSelf, data) in
print(strongSelf)
print(data)
})
}
}
PlaygroundPage.current.liveView = MyVC()
func loadData(_ completion: @escaping ([String]) -> Void) {
DispatchQueue.global(qos: .background).async {
Thread.sleep(forTimeInterval: 2)
DispatchQueue.main.async {
completion((0...100).map { String(describing: $0) })
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment