Skip to content

Instantly share code, notes, and snippets.

@JoshuaSullivan
Created March 3, 2016 16:37
Show Gist options
  • Save JoshuaSullivan/c0dc873c7d48cee1c1c4 to your computer and use it in GitHub Desktop.
Save JoshuaSullivan/c0dc873c7d48cee1c1c4 to your computer and use it in GitHub Desktop.
Code snippets for my blog post about functions which return optional values vs functions that throw errors.
import Swift
/// This method returns half of the input value if the number is even. It returns nil if the number is odd.
func evenHalfOrNil(input: Int) -> Int? {
if (input % 2 == 0) {
return input / 2
} else {
return nil
}
}
func test() {
// guard let handling
guard let halfOfFour = evenHalfOrNil(4) else {
print("It would seem that 4 is not even!?")
// Exit current scope.
return
}
print("halfOfFour:", halfOfFour)
// if let handling
if let _ = evenHalfOrNil(7) {
print("Huh! It seems like 7 is even. Who knew?")
} else {
print("As I expected! 7 is not even.")
}
// nil coalescing
let randomInt = Int(arc4random_uniform(10))
print("randomInt:", randomInt)
let evenOrZero = evenHalfOrNil(randomInt) ?? 0
print("evenOrZero:", evenOrZero)
}
test()
/// Our enumeration of error conditions.
enum NumberProcessingError: ErrorType {
case OddInput, NegativeInput
}
/// Accepts positive, even integers and returns half their value.
/// We're not using UInt because reasons.
func processNumber(input: Int) throws -> Int {
guard input >= 0 else {
throw NumberProcessingError.NegativeInput
}
guard input % 2 == 0 else {
throw NumberProcessingError.OddInput
}
return input / 2
}
func testProcessorWithOptionalTry() {
// Ignore the errors and treat them as nil returns.
if let halfThree = try? processNumber(-3) {
print("halfThree:", halfThree)
} else {
print("Something went wrong, but I don't care. On with the show!")
}
}
func testProcessorWithErrorHandling(testValue: Int) {
// Handle the errors.
print("Attempting to process:", testValue)
do {
let result = try processNumber(testValue)
print("Success! Here's the result:", result)
} catch NumberProcessingError.NegativeInput {
print("Negative input value. Consider using", abs(testValue))
} catch NumberProcessingError.OddInput {
print("The input must be even. Consider using", testValue + 1)
} catch {
print("An error occurred which we are not going to handle:", error)
}
}
testProcessorWithOptionalTry()
testProcessorWithErrorHandling(3)
testProcessorWithErrorHandling(-12)
testProcessorWithErrorHandling(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment