0
0
Swiftprogramming~20 mins

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

Choose your learning style9 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.