What if you could try risky code without the headache of messy error checks?
Why Try? for optional result in Swift? - Purpose & Use Cases
Imagine you have a function that might fail, like reading a file or converting text to a number. Without a simple way to handle errors, you have to write lots of code to check if it worked or not.
Manually checking for errors every time is slow and makes your code messy. It's easy to forget to handle some errors, which can cause your app to crash or behave unexpectedly.
Using try? lets you run code that might fail and automatically get a simple optional result. If it works, you get the value; if it fails, you get nil. This keeps your code clean and safe without extra error handling.
do {
let result = try someFunction()
print(result)
} catch {
print("Failed")
}if let result = try? someFunction() { print(result) } else { print("Failed") }
You can quickly and safely try risky operations and handle failures gracefully with minimal code.
When loading user settings from a file, try? lets you attempt to read the file and get nil if it's missing or corrupted, so your app can use default settings instead.
Try? simplifies error handling by returning an optional result.
It reduces code clutter and prevents crashes from unhandled errors.
It's perfect for quick, safe attempts at operations that might fail.
Practice
try? do when used with a throwing function in Swift?Solution
Step 1: Understand try? behavior
Thetry?keyword runs a throwing function and converts its result into an optional value.Step 2: What happens on error?
If the function throws an error,try?returnsnilinstead of crashing or propagating the error.Final Answer:
It runs the function and returns an optional result, nil if an error occurs. -> Option AQuick Check:
try? returns optional or nil on error [OK]
- Thinking try? crashes on error
- Assuming try? prints error messages
- Believing try? converts errors to strings
try? with a throwing function named loadData()?Solution
Step 1: Identify correct try? syntax
The correct syntax requirestry?followed by the function call with parentheses.Step 2: Check each option
let data = try loadData() usestrywithout ?, which doesn't return optional. let data = try! loadData() usestry!which forces crash on error. let data = try?loadData misses parentheses after function name.Final Answer:
let data = try? loadData() -> Option DQuick Check:
try? requires parentheses for function call [OK]
- Omitting parentheses after function name
- Using try without ? for optional
- Using try! which forces crash on error
func fetchNumber() throws -> Int {
if Bool.random() { return 10 } else { throw NSError() }
}
let result = try? fetchNumber()
print(result)What are possible outputs?
Solution
Step 1: Understand fetchNumber behavior
The function randomly returns 10 or throws an error.Step 2: Effect of try? on fetchNumber
Usingtry?converts the throwing call into an optional Int. If no error, it returnsOptional(10). If error, it returnsnil.Final Answer:
Prints either Optional(10) or nil -> Option AQuick Check:
try? returns optional or nil based on error [OK]
- Assuming always returns value
- Assuming always returns nil
- Expecting a crash on error
func readFile() throws -> String {
throw NSError()
}
let content = try readFile()
print(content)Solution
Step 1: Check error handling in calling code
The functionreadFile()throws an error, but the call uses plaintrywithout handling errors.Step 2: Fix error handling with try?
Usingtry?converts the throwing call into an optional, preventing runtime crash and handling error gracefully.Final Answer:
Missing try? to handle error as optional -> Option CQuick Check:
Use try? to avoid crash on throwing function [OK]
- Using try without catch or try?
- Assuming throwing function never throws
- Thinking print causes error
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?Solution
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.Step 2: Use try? with nil coalescing
Usingtry?converts the throwing call to optional. The?? [:]provides empty dictionary if nil.Final Answer:
let dict = try? parseData() ?? [:] -> Option BQuick Check:
try? with ?? gives safe default on error [OK]
- Using try without ? causes crash on error
- Using try! forces crash on error
- Calling throwing function without try
Ready to prove it?
Pass the test and this pattern moves unknown
