Skip to content

Instantly share code, notes, and snippets.

@ansonj
Created May 28, 2020 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ansonj/204f330cf61a9700fe3a77fd903b3ee8 to your computer and use it in GitHub Desktop.
Save ansonj/204f330cf61a9700fe3a77fd903b3ee8 to your computer and use it in GitHub Desktop.
Throwing inside a guard
/// 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")
*/
@ansonj
Copy link
Author

ansonj commented May 28, 2020

Also, I learned that these produce the same output:

try print(callingFunction_returnString())
print(try callingFunction_returnString())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment