Concept Flow - Try? for optional result
Call throwing function
Try? catches error?
Return value
Use optional result
Try? calls a function that might throw an error. If no error, it returns the value wrapped as optional. If error, it returns nil.
enum ParseError: Error { case invalidFormat } func parseInt(_ str: String) throws -> Int { if let num = Int(str) { return num } else { throw ParseError.invalidFormat } } let result = try? parseInt("123")
| Step | Action | Function Call Result | Try? Result | Notes |
|---|---|---|---|---|
| 1 | Call parseInt("123") | Returns 123 | Optional(123) | String "123" converts successfully |
| 2 | Call parseInt("abc") | Throws error | nil | String "abc" cannot convert, error caught by try? |
| 3 | Use result from try? | N/A | Optional(123) or nil | Result is optional Int or nil if error |
| Variable | Start | After 1 | After 2 | Final |
|---|---|---|---|---|
| result | nil | Optional(123) | nil | Depends on input string |
try? calls a throwing function and returns an optional result. If function succeeds, try? returns Optional(value). If function throws error, try? returns nil. Use try? to safely handle errors without do-catch. Result type is always optional of function's return type.
try? do when used with a throwing function in Swift?try? keyword runs a throwing function and converts its result into an optional value.try? returns nil instead of crashing or propagating the error.try? with a throwing function named loadData()?try? followed by the function call with parentheses.try without ?, which doesn't return optional. let data = try! loadData() uses try! which forces crash on error. let data = try?loadData misses parentheses after function name.func fetchNumber() throws -> Int {
if Bool.random() { return 10 } else { throw NSError() }
}
let result = try? fetchNumber()
print(result)try? converts the throwing call into an optional Int. If no error, it returns Optional(10). If error, it returns nil.func readFile() throws -> String {
throw NSError()
}
let content = try readFile()
print(content)readFile() throws an error, but the call uses plain try without handling errors.try? converts the throwing call into an optional, preventing runtime crash and handling error gracefully.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?try? converts the throwing call to optional. The ?? [:] provides empty dictionary if nil.Pass the test and this pattern moves unknown