Bird
Raised Fist0
Swiftprogramming~20 mins

Try? for optional result in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Try? Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code using try?

Consider this Swift code that uses try? to handle errors. What will be printed?

Swift
enum SampleError: Error {
    case fail
}

func mightThrow(_ shouldThrow: Bool) throws -> Int {
    if shouldThrow {
        throw SampleError.fail
    }
    return 42
}

let result = try? mightThrow(true)
print(result ?? "nil")
A42
BRuntime error
CSampleError.fail
Dnil
Attempts:
2 left
💡 Hint

Remember that try? converts errors into nil instead of throwing.

❓ Predict Output
intermediate
2:00remaining
What does this code print when try? succeeds?

What will be printed by this Swift code?

Swift
func safeDivide(_ a: Int, _ b: Int) throws -> Int {
    if b == 0 { throw NSError(domain: "", code: 1) }
    return a / b
}

let result = try? safeDivide(10, 2)
print(result ?? "nil")
A5
Bnil
C0
DRuntime error
Attempts:
2 left
💡 Hint

When no error is thrown, try? returns the value wrapped in an optional.

🔧 Debug
advanced
2:00remaining
Why does this code print nil instead of the value?

Look at this Swift code snippet. It prints "nil" even though the function seems to return a value. Why?

Swift
enum MyError: Error {
    case error
}

func test() throws -> Int {
    return 10
}

let value = try? test()
print(value ?? "nil")
AThe function throws an error, so try? returns nil
BThe code has a syntax error and does not compile
CThe function returns 10, so try? returns Optional(10)
DThe print statement is incorrect and prints nil
Attempts:
2 left
💡 Hint

Check if the function actually throws an error or not.

📝 Syntax
advanced
2:00remaining
Which option causes a compile-time error with try??

Which of these Swift code snippets will cause a compile-time error?

Alet result = try someThrowingFunction()
Blet result = try?? someThrowingFunction()
Clet result = try! someThrowingFunction()
Dlet result = try? someThrowingFunction()
Attempts:
2 left
💡 Hint

Check the correct syntax for using try with optional chaining.

🚀 Application
expert
3:00remaining
How many items are in the array after filtering with try??

Given this Swift code, how many elements are in the results array after filtering?

Swift
enum ParseError: Error {
    case invalid
}

func parse(_ s: String) throws -> Int {
    guard let value = Int(s) else { throw ParseError.invalid }
    return value
}

let inputs = ["1", "two", "3", "four"]
let results = inputs.compactMap { try? parse($0) }
A2
B3
C4
D0
Attempts:
2 left
💡 Hint

Count how many strings can be converted to Int without throwing.

Practice

(1/5)
1. What does try? do when used with a throwing function in Swift?
easy
A. It runs the function and returns an optional result, nil if an error occurs.
B. It forces the function to crash if an error is thrown.
C. It catches the error and prints it automatically.
D. It converts the error into a string message.

Solution

  1. Step 1: Understand try? behavior

    The try? keyword runs a throwing function and converts its result into an optional value.
  2. Step 2: What happens on error?

    If the function throws an error, try? returns nil instead of crashing or propagating the error.
  3. Final Answer:

    It runs the function and returns an optional result, nil if an error occurs. -> Option A
  4. Quick Check:

    try? returns optional or nil on error [OK]
Hint: try? returns nil on error instead of crashing [OK]
Common Mistakes:
  • Thinking try? crashes on error
  • Assuming try? prints error messages
  • Believing try? converts errors to strings
2. Which of the following is the correct syntax to use try? with a throwing function named loadData()?
easy
A. let data = try loadData()
B. let data = try! loadData()
C. let data = try?loadData
D. let data = try? loadData()

Solution

  1. Step 1: Identify correct try? syntax

    The correct syntax requires try? followed by the function call with parentheses.
  2. Step 2: Check each option

    let data = try loadData() uses try without ?, which doesn't return optional. let data = try! loadData() uses try! which forces crash on error. let data = try?loadData misses parentheses after function name.
  3. Final Answer:

    let data = try? loadData() -> Option D
  4. Quick Check:

    try? requires parentheses for function call [OK]
Hint: Use try? followed by function call with parentheses [OK]
Common Mistakes:
  • Omitting parentheses after function name
  • Using try without ? for optional
  • Using try! which forces crash on error
3. Consider this Swift code:
func fetchNumber() throws -> Int {
  if Bool.random() { return 10 } else { throw NSError() }
}

let result = try? fetchNumber()
print(result)

What are possible outputs?
medium
A. Prints either Optional(10) or nil
B. Always prints Optional(10)
C. Always prints nil
D. Causes a runtime crash

Solution

  1. Step 1: Understand fetchNumber behavior

    The function randomly returns 10 or throws an error.
  2. Step 2: Effect of try? on fetchNumber

    Using try? converts the throwing call into an optional Int. If no error, it returns Optional(10). If error, it returns nil.
  3. Final Answer:

    Prints either Optional(10) or nil -> Option A
  4. Quick Check:

    try? returns optional or nil based on error [OK]
Hint: try? returns optional value or nil on error [OK]
Common Mistakes:
  • Assuming always returns value
  • Assuming always returns nil
  • Expecting a crash on error
4. Identify the error in this Swift code snippet:
func readFile() throws -> String {
  throw NSError()
}

let content = try readFile()
print(content)
medium
A. print(content) is invalid syntax
B. Function readFile() should not throw error
C. Missing try? to handle error as optional
D. No error, code runs fine

Solution

  1. Step 1: Check error handling in calling code

    The function readFile() throws an error, but the call uses plain try without handling errors.
  2. Step 2: Fix error handling with try?

    Using try? converts the throwing call into an optional, preventing runtime crash and handling error gracefully.
  3. Final Answer:

    Missing try? to handle error as optional -> Option C
  4. Quick Check:

    Use try? to avoid crash on throwing function [OK]
Hint: Use try? to safely call throwing functions without crash [OK]
Common Mistakes:
  • Using try without catch or try?
  • Assuming throwing function never throws
  • Thinking print causes error
5. You want to call a throwing function parseData() that returns a dictionary, but you want to safely get an empty dictionary if it fails. Which code correctly uses try? to achieve this?
hard
A. let dict = try parseData() ?? [:]
B. let dict = try? parseData() ?? [:]
C. let dict = try! parseData() ?? [:]
D. let dict = parseData() ?? [:]

Solution

  1. Step 1: Understand requirement for safe call

    You want to call a throwing function and get an optional result, defaulting to empty dictionary if it fails.
  2. Step 2: Use try? with nil coalescing

    Using try? converts the throwing call to optional. The ?? [:] provides empty dictionary if nil.
  3. Final Answer:

    let dict = try? parseData() ?? [:] -> Option B
  4. Quick Check:

    try? with ?? gives safe default on error [OK]
Hint: Combine try? with ?? to provide default value [OK]
Common Mistakes:
  • Using try without ? causes crash on error
  • Using try! forces crash on error
  • Calling throwing function without try
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard