0
0
Swiftprogramming~10 mins

Try? for optional result in Swift - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Swift
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")
This code tries to convert a string to an integer. If it works, result is the number wrapped as optional. If it fails, result is nil.
Execution Table
StepActionFunction Call ResultTry? ResultNotes
1Call parseInt("123")Returns 123Optional(123)String "123" converts successfully
2Call parseInt("abc")Throws errornilString "abc" cannot convert, error caught by try?
3Use result from try?N/AOptional(123) or nilResult is optional Int or nil if error
💡 Execution stops after try? returns optional value or nil depending on success or error
Variable Tracker
VariableStartAfter 1After 2Final
resultnilOptional(123)nilDepends on input string
Key Moments - 2 Insights
Why does try? return nil instead of crashing when an error happens?
Because try? catches the error internally and converts it to nil, as shown in execution_table row 2.
What type is the result variable after using try??
It is an optional type wrapping the function's return type, shown as Optional(123) or nil in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what does try? return when parseInt throws an error?
AThe error is thrown up and crashes the program
BAn optional wrapping the error
Cnil
DA default value like 0
💡 Hint
See execution_table row 2 where try? result is nil when error occurs
At which step does try? return Optional(123)?
AStep 2
BStep 1
CStep 3
DNever
💡 Hint
Check execution_table row 1 where parseInt returns 123 and try? wraps it
If parseInt always succeeds, how does variable_tracker for result change?
Aresult becomes Optional with value every time
Bresult stays nil
Cresult becomes non-optional Int
Dresult becomes an error
💡 Hint
See variable_tracker showing result changes to Optional(123) after success
Concept Snapshot
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.
Full Transcript
In Swift, try? is used to call a function that might throw an error. Instead of crashing or requiring a do-catch block, try? catches any error and returns nil. If the function succeeds, try? returns the value wrapped as an optional. For example, calling try? parseInt("123") returns Optional(123). Calling try? parseInt("abc") returns nil because the string cannot be converted. This lets you handle errors simply by checking if the result is nil or not. The variable holding the try? result is always an optional type. This visual trace shows each step: calling the function, catching errors, and returning optional values or nil. Remember, try? is a safe way to get optional results from throwing functions.