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 thrown1enum ValidationError: Error {2 case tooShort3 case invalidFormat4}5 // throws marks a function that can throw an error6func validate(_ input: String) throws -> String { // Fewer than 3 characters: throws tooShort7 guard input.count >= 3 else { throw ValidationError.tooShort } // first is optional, so compare with == true; not a letter: throws invalidFormat8 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: Hello13 print(try validate("Hello")) // Throws tooShort: the rest of the do block is skipped14 print(try validate("Hi"))// A catch with a pattern handles only that specific error15} catch ValidationError.tooShort { // Runs here: prints Input too short16 print("Input too short")// A plain catch handles every other error17} catch {18 print("Other error")19}Output
Valid: Hello Input too short
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