1. Define asynchronous return types

Creating a Success or failure enumeration Custom Description is returned on success, custom description is returned on failure [errorStr]

enum createResult {
    case success(successStr:String)
    case error(errorStr:String)
}
Copy the code

2. Request method

.success is the type of successful callback defined by createResult. Error is the type of successful callback defined by createResult

/ / request successfully returns the custom description [successStr], request return the custom description [errorStr] failure func create (name: String, completionHandler: @escaping(createResult) -> Void) {dispatchqueue.global ().async {// Simulate request blocking within Http threads for 3 seconds sleep(3) // Simulate return successful callback CompletionHandler (. Success (successStr: "Request successful name = \(name)")) // Simulation returns a failure callback completionHandler(. Error (errorStr: "Request failed name = \(name)"))}}Copy the code

3. Call methods externally

An external call is made to the method that simulates the request and receives success and failure

Create (name: "xinG") {result in switch result{case.error (let errorStr): print("Error:\(errorStr)") break; Case. Success (let successStr): print(" success: operation successful)") print("Success:\(successStr)") break}}Copy the code

conclusion

Such processing can be used externally to block, through the form of enumeration, can tell the calling object internal processing status, semantics are very clear.

The complete code snippet

enum NetworkError: Error {case badURL} // Custom description [successStr], [errorStr] enum createResult {case Success (successStr:String) case Error (errorStr:String)} / / request successfully returns the custom description [successStr], request return the custom description [errorStr] failure func create (name: String, completionHandler: @escaping(createResult) -> Void) {dispatchqueue.global ().async {// Simulate request blocking within Http threads for 3 seconds sleep(3) // Simulate return successful callback CompletionHandler (. Success (successStr: "Request successful name = \(name)")) // Simulation returns a failure callback completionHandler(. Error (errorStr: "Request failed name = \(name)"))}} // External call to simulate the request method and receive the success and failure of create(name: "xinG") { result in switch result{ case .error(let errorStr): print("Error:\(errorStr)") break; case .success(let successStr): Print (" successStr ") print("Success:\(successStr)") break}} print("==end") sleep(1000)Copy the code