Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

func onMainDo<T>(_ firstMainBlock: @escaping () -> Void, onBackgroundDo backgroundBlock: @escaping () -> T, thenOnMainDo mainBlock: @escaping (T) -> Void) {
DispatchQueue.main.async {
firstMainBlock()
DispatchQueue.global(qos: .background).async {
let result = backgroundBlock()
DispatchQueue.main.async {
mainBlock(result)
}
}
}
let service = SyncronousThingsService()
onMainDo({
self.activityIndicator.startAnimating()
}, onBackgroundDo: {
return service.getThings()
}, thenOnMainDo: {
self.activityIndicator.stopAnimating()
self.updateUI(with: $0)
})
let syncService = SyncronicThingsService()
activityIndicator.startAnimating()
DispatchQueue.global(qos: .background).async {
let getThingsResult = syncService.getThings()
DispatchQueue.main.async {
activityIndicator.stopAnimating()
updateUI(with: getThingsResult)
}
}
let service = ThingsService()
activityIndicator.startAnimating()
service.getThings { getThingsResult in
activityIndicator.stopAnimating()
updateUI(with: getThingsResult)
}
class ThingsService {
func getThings() -> Result<[Thing]> {
do {
let response = try sendHttpRequestSynchronously(url)
let data = try getData(from: response)
let things = try doParsing(data)
return .success(things)
} catch error {
return .failure(error)
}
class ThingsService {
func getThings(onCompletion callback: @escaping (Result<[Thing]>) -> Void) {
sendHttpRequestAsynchronously(url) { response in
DispatchQueue.main.async {
do {
let data = try getData(from: response)
let things = try doParsing(data)
callback(.success(things)))
} catch error {
callback(.failure(error))
class Tap {
private static var instances: [Tap] = []
// ...
static func on(view: UIView, fires action: @escaping () -> Void) {
let tap = Tap(view: view, action: action)
Tap.instances.append(tap)
}
class Tap {
private var view: UIView
private var action: () -> Void
init(view: UIView, action: @escaping () -> Void) {
self.view = view
self.action = action
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTap(_:)))
view.addGestureRecognizer(tapGesture)
func aMethod() {
aView.onTap { /* action */ }
// or
Tap.on(aView) { /* action */ }
}
func aMethod() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTap(_:)))
aView.addGestureRecognizer(tapGesture)
}
@objc func onTap(_ gesture: UIGestureRecognizer) {
if (gesture.state == .ended) {
/* action */
}
}