Consider this Swift code that uses try? to handle errors. What will be printed?
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")
Remember that try? converts errors into nil instead of throwing.
The function throws an error because shouldThrow is true. Using try? converts the thrown error into nil, so result is nil. The print statement prints "nil".
What will be printed by this Swift code?
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")
When no error is thrown, try? returns the value wrapped in an optional.
The division succeeds (10 / 2 = 5), so try? returns Optional(5). The print statement unwraps it and prints 5.
Look at this Swift code snippet. It prints "nil" even though the function seems to return a value. Why?
enum MyError: Error { case error } func test() throws -> Int { return 10 } let value = try? test() print(value ?? "nil")
Check if the function actually throws an error or not.
The function test() does not throw an error; it returns 10. Using try? wraps the result in an optional. So value is Optional(10), and the print statement prints 10.
Which of these Swift code snippets will cause a compile-time error?
Check the correct syntax for using try with optional chaining.
Using try?? is invalid syntax in Swift. The correct forms are try?, try!, or try. Option B causes a compile-time error.
Given this Swift code, how many elements are in the results array after filtering?
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) }
Count how many strings can be converted to Int without throwing.
Only "1" and "3" can be converted to Int without error. The others throw errors, so try? returns nil for them. compactMap removes nils, so the array has 2 elements.