Created
May 28, 2020 14:38
-
-
Save ansonj/204f330cf61a9700fe3a77fd903b3ee8 to your computer and use it in GitHub Desktop.
Throwing inside a guard
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
/// Lesson learned: | |
/// Inside a throwing function... | |
/// if a `guard` condition calls a second function that ends up throwing... | |
/// the second function's error is immediately propagated outside of the function. | |
/// Execution does not enter the `else` block of the `guard` clause. | |
struct PlaygroundError: Error { | |
let message: String | |
} | |
enum DesiredAction { | |
case throwSomething | |
case returnNil | |
case returnString | |
} | |
func performAction(_ action: DesiredAction) throws -> String? { | |
switch action { | |
case .throwSomething: | |
throw PlaygroundError(message: "I'm throwing from inside the method") | |
case .returnNil: | |
return nil | |
case .returnString: | |
return "Here's a valid string for you" | |
} | |
} | |
func callingFunction_throw() throws -> String { | |
guard let stringValue = try performAction(.throwSomething) else { | |
throw PlaygroundError(message: "This is an error from the calling function, which I don't want to see") | |
} | |
return stringValue | |
} | |
func callingFunction_returnNil() throws -> String { | |
guard let stringValue = try performAction(.returnNil) else { | |
throw PlaygroundError(message: "This is an error from the calling function, which I don't want to see") | |
} | |
return stringValue | |
} | |
func callingFunction_returnString() throws -> String { | |
guard let stringValue = try performAction(.returnString) else { | |
throw PlaygroundError(message: "This is an error from the calling function, which I don't want to see") | |
} | |
return stringValue | |
} | |
print("1: return string") | |
do { | |
try print(callingFunction_returnString()) | |
} catch let error { | |
print("Error:", error) | |
} | |
print("2: return nil") | |
do { | |
try print(callingFunction_returnNil()) | |
} catch let error { | |
print("Error:", error) | |
} | |
print("3: throw") | |
do { | |
try print(callingFunction_throw()) | |
} catch let error { | |
print("Error:", error) | |
} | |
/* | |
1: return string | |
Here's a valid string for you | |
2: return nil | |
Error: PlaygroundError(message: "This is an error from the calling function, which I don\'t want to see") | |
3: throw | |
Error: PlaygroundError(message: "I\'m throwing from inside the method") | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, I learned that these produce the same output: