Created
November 29, 2017 02:36
-
-
Save myobie/7fc8a7573b3c485dbffa3afb020da583 to your computer and use it in GitHub Desktop.
An example of swift async callbacks that either throw or return a result
This file contains 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 Foundation | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
// either throws an Error or returns a String result | |
typealias ThrowsCallback = () throws -> (String) | |
enum AsyncError: Error { | |
case kaboom | |
} | |
func asyncActionWithCallback(_ someData: String, callback: @escaping (ThrowsCallback) -> Void) { | |
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { | |
if someData == "please error" { | |
callback({ throw AsyncError.kaboom }) | |
} else { | |
callback({ return "you provided \(someData)" }) | |
} | |
} | |
} | |
asyncActionWithCallback("Hello") { result in | |
let value = try? result() | |
print(String(describing: value)) | |
} | |
asyncActionWithCallback("please error") { result in | |
let value = try? result() | |
print(String(describing: value)) | |
PlaygroundPage.current.finishExecution() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment