Created
April 10, 2020 07:26
-
-
Save hoc081098/8e1395953fe6242d2910cbea8d001f0f to your computer and use it in GitHub Desktop.
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
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