Bird
Raised Fist0
Swiftprogramming~20 mins

Try! for forced unwrap in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift 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 force unwrap a throwing function. What will it print?
Swift
enum FileError: Error {
    case fileNotFound
}

func readFile(_ name: String) throws -> String {
    if name == "exists.txt" {
        return "File content"
    } else {
        throw FileError.fileNotFound
    }
}

let content = try! readFile("exists.txt")
print(content)
Anil
BCompilation error
CRuntime error: fileNotFound
DFile content
Attempts:
2 left
💡 Hint
try! forces the function to succeed or crash if it throws.
❓ Predict Output
intermediate
2:00remaining
What happens when try! unwraps a throwing function that fails?
What is the result of running this Swift code?
Swift
enum ParseError: Error {
    case invalidFormat
}

func parseNumber(_ str: String) throws -> Int {
    guard let num = Int(str) else {
        throw ParseError.invalidFormat
    }
    return num
}

let number = try! parseNumber("abc")
print(number)
ARuntime crash with invalidFormat error
BCompilation error
CPrints nil
DPrints 0
Attempts:
2 left
💡 Hint
try! crashes if the function throws an error.
🧠 Conceptual
advanced
1:30remaining
Why is using try! risky in Swift?
Which of the following best explains the risk of using try! in Swift?
AIt can cause runtime crashes if the throwing function actually throws an error.
BIt always catches errors and handles them silently.
CIt converts errors into optional values automatically.
DIt prevents the function from throwing any errors.
Attempts:
2 left
💡 Hint
Think about what happens if the function throws an error when using try!.
❓ Predict Output
advanced
2:00remaining
What is the output of this Swift code with try! and do-catch?
What will this Swift code print?
Swift
enum NetworkError: Error {
    case disconnected
}

func fetchData() throws -> String {
    throw NetworkError.disconnected
}

var result = ""
do {
    result = try fetchData()
} catch {
    result = "Error caught"
}

print(try! fetchData())
AError caught
BRuntime crash with disconnected error
CCompilation error
DEmpty string
Attempts:
2 left
💡 Hint
The do-catch block handles the error, but try! outside does not.
🔧 Debug
expert
2:30remaining
Identify the line causing a runtime crash with try! in this Swift code
Which line causes a runtime crash when running this Swift code?
Swift
enum DataError: Error {
    case missingData
}

func loadData(_ key: String) throws -> String {
    if key == "valid" {
        return "Data loaded"
    } else {
        throw DataError.missingData
    }
}

let a = try! loadData("valid")
let b = try! loadData("invalid")
print(a)
print(b)
Aprint(a)
Blet a = try! loadData("valid")
Clet b = try! loadData("invalid")
Dprint(b)
Attempts:
2 left
💡 Hint
One call uses a key that causes an error to be thrown.

Practice

(1/5)
1. What does try! do in Swift when calling a function that can throw an error?
easy
A. It catches errors and handles them gracefully.
B. It converts the error into a warning message.
C. It ignores the function and returns nil.
D. It runs the function and forces the result without catching errors.

Solution

  1. Step 1: Understand the role of try!

    try! runs a throwing function but does not catch errors.
  2. Step 2: Recognize the behavior on error

    If an error occurs, the program crashes instead of handling it.
  3. Final Answer:

    It runs the function and forces the result without catching errors. -> Option D
  4. Quick Check:

    try! forces result without error handling [OK]
Hint: Remember: try! crashes on error, no catch block used [OK]
Common Mistakes:
  • Thinking try! catches errors
  • Assuming try! returns nil on error
  • Confusing try! with try?
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 = loadData()!

Solution

  1. Step 1: Recall correct try! syntax

    The forced try syntax is try! followed by the function call.
  2. Step 2: Match syntax to options

    let data = try! loadData() uses try! correctly before loadData().
  3. Final Answer:

    let data = try! loadData() -> Option A
  4. Quick Check:

    Correct forced try syntax = let data = try! loadData() [OK]
Hint: Use try! directly before the function call without parentheses [OK]
Common Mistakes:
  • Using try without ! for forced unwrap
  • Using try? which returns optional
  • Adding ! after function call incorrectly
3. Consider this Swift code:
func getNumber() throws -> Int {
  return 42
}

let result = try! getNumber()
print(result)

What will be the output when this code runs?
medium
A. nil
B. 42
C. Runtime error
D. Compilation error

Solution

  1. Step 1: Analyze the throwing function

    getNumber() always returns 42 and does not throw an error.
  2. Step 2: Understand try! behavior here

    Since no error occurs, try! unwraps the result safely.
  3. Final Answer:

    42 -> Option B
  4. Quick Check:

    No error thrown, so output is 42 [OK]
Hint: If no error thrown, try! returns value directly [OK]
Common Mistakes:
  • Expecting runtime error even if no error thrown
  • Thinking try! returns optional
  • Confusing with try? behavior
4. What is the problem with this Swift code?
func fail() throws -> String {
  throw NSError(domain: "Error", code: 1)
}

let text = try! fail()
print(text)
medium
A. It causes a runtime crash due to forced unwrap of error.
B. It compiles but prints an empty string.
C. It returns nil without crashing.
D. It causes a compile-time error.

Solution

  1. Step 1: Identify the throwing function behavior

    fail() always throws an error when called.
  2. Step 2: Understand try! effect on error

    try! forces unwrap and crashes if an error is thrown.
  3. Final Answer:

    It causes a runtime crash due to forced unwrap of error. -> Option A
  4. Quick Check:

    try! crashes on thrown error [OK]
Hint: try! crashes if error thrown, no catch block used [OK]
Common Mistakes:
  • Expecting graceful error handling
  • Thinking it returns nil on error
  • Assuming compile-time error
5. You have a function that reads a configuration file and throws an error if the file is missing:
func readConfig() throws -> String {
  // throws if file missing
  return "Config data"
}

You want to use try! safely. Which approach is best to avoid crashing your app?
hard
A. Replace try! with try? and ignore errors.
B. Always use try! without any checks.
C. Use try! only after checking the file exists.
D. Use try! inside a do-catch block.

Solution

  1. Step 1: Understand try! risk

    try! crashes if an error occurs, so it must be used only when sure no error happens.
  2. Step 2: Apply safe usage

    Checking file existence before calling try! ensures no error will be thrown.
  3. Final Answer:

    Use try! only after checking the file exists. -> Option C
  4. Quick Check:

    Safe use of try! requires prior error prevention [OK]
Hint: Check conditions before try! to avoid crashes [OK]
Common Mistakes:
  • Using try! blindly without checks
  • Ignoring errors with try?
  • Misusing try! inside do-catch
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