Error Handling in Swift

Level 5440 keystrokes

validate throws a custom ValidationError when the input is too short or does not start with a letter. "Hello" passes, but "Hi" throws tooShort, so the do block stops there and the matching catch prints Input too short.

Swift code

// Any type conforming to Error can be thrown
1enum ValidationError: Error {
2 case tooShort
3 case invalidFormat
4}
5
// throws marks a function that can throw an error
6func validate(_ input: String) throws -> String {
// Fewer than 3 characters: throws tooShort
7 guard input.count >= 3 else { throw ValidationError.tooShort }
// first is optional, so compare with == true; not a letter: throws invalidFormat
8 guard input.first?.isLetter == true else { throw ValidationError.invalidFormat }
9 return "Valid: \(input)"
10}
11
12do {
// try is required to call a throwing function; prints Valid: Hello
13 print(try validate("Hello"))
// Throws tooShort: the rest of the do block is skipped
14 print(try validate("Hi"))
// A catch with a pattern handles only that specific error
15} catch ValidationError.tooShort {
// Runs here: prints Input too short
16 print("Input too short")
// A plain catch handles every other error
17} catch {
18 print("Other error")
19}

Output

Valid: Hello
Input too short
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • "× 10
  • (× 8
  • )× 8
  • {× 7
  • }× 7
  • .× 6
  • :× 3
  • =× 3
  • >× 2
  • _× 1

More Swift examples at level 5

← Swift typing practice