0
0
Swiftprogramming~20 mins

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

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