Skip to content
Justice Tech School

try? and try!

try? turns errors into nil and try! crashes on error.

Example
func parse(_ s: String) throws -> Int { guard let n = Int(s) else { throw NSError(domain: "x", code: 1) }; return n }
print(try? parse("42") as Any)
print((try? parse("x")) ?? -1)

Exercise

Turn errors into nil.

? parse("x")

Quiz Test

What does try? return on error?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.