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.