Created
August 19, 2022 07:18
-
-
Save samuelowino/c8ed35c6edcc223896877e0d11ff26e4 to your computer and use it in GitHub Desktop.
Defer statements
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 Foundation | |
| enum BadRequestException: Error { | |
| case NetworkRequestFailed(cause: String) | |
| } | |
| struct NetworkConnection { | |
| var openStatus: Bool | |
| } | |
| func get() throws { | |
| throw BadRequestException.NetworkRequestFailed(cause: "Api request failed for reasons...") | |
| } | |
| func makeApiRequest() { | |
| var networkConnection = NetworkConnection(openStatus: false) | |
| do { | |
| networkConnection.openStatus = true | |
| try get() | |
| } catch { | |
| print("Api request failed but connection was closed and update to \(error)") | |
| } | |
| if networkConnection.openStatus == true { | |
| defer { | |
| //close this connection regardless | |
| networkConnection.openStatus = false | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment