Menu
Coddy logo textTech

try? and try!

Part of the Logic & Flow section of Coddy's Swift journey — lesson 46 of 56.

Sometimes you don't care which error a function threw, you just want a result or a fallback. Swift gives you two short forms.

try? turns any thrown error into nil. The result is an Optional of the function's return type:

enum E: Error { case nope }
func risky() throws -> Int { throw E.nope }

let result = try? risky()        // nil
let safe   = (try? risky()) ?? 0 // 0

Pair it with ?? for an inline default. This is the shortest version of "call this thing, give me a value either way".

try! says "I know this won't throw". If it does, your program crashes. Use it only when you can prove the call is safe; in everyday code, prefer try? with a fallback or the full do/catch.

challenge icon

Challenge

Easy

Define NumError: Error with one case bad. Define a throwing parseEven(_ s: String) throws -> Int that:

  • Throws .bad when s can't be parsed as Int, or when the parsed value is odd
  • Otherwise returns the parsed integer

Read a single line of input: a comma-separated list of strings. For each one, use try? followed by ?? -1 to either get the parsed even integer or -1.

Print, in order, the resulting integers joined with ,. Then on a second line print the count of values that came back as -1.

For input 4,7,abc,8,11,2, the output is:

4,-1,-1,8,-1,2
3

Cheat sheet

try? converts a thrown error into nil, returning an Optional:

let result = try? risky()        // nil on throw
let safe   = (try? risky()) ?? 0 // fallback value

try! crashes if the call throws — only use when the call is guaranteed safe:

let value = try! guaranteedSafe()

Try it yourself

let parts = readLine()!.components(separatedBy: ",")

// TODO: enum NumError; func parseEven(_:) throws -> Int;
// for each part, (try? parseEven(part)) ?? -1
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow