0
0
Swiftprogramming~5 mins

Try? for optional result in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does try? do in Swift?

try? attempts to run a function that can throw an error. If the function succeeds, it returns an optional with the result. If it throws an error, it returns nil instead of crashing.

Click to reveal answer
beginner
How is try? different from try!?

try? returns an optional and safely handles errors by returning nil. try! forces the call and crashes if an error is thrown.

Click to reveal answer
beginner
What type does a function call with try? return?

It returns an optional type wrapping the function's return type. For example, if the function returns Int, try? returns Int?.

Click to reveal answer
beginner
Example: What is the output of <code>let result = try? Int("123")</code>?

The output is Optional(123) because the string "123" can be converted to an integer successfully.

Click to reveal answer
beginner
Example: What happens with <code>let result = try? Int("abc")</code>?

The output is nil because "abc" cannot be converted to an integer, so the error is caught and nil is returned.

Click to reveal answer
What does try? return if the function throws an error?
AThe function's normal return value
BThe error itself
CIt crashes the program
Dnil
Which of these is true about try? in Swift?
AIt converts errors into optional nil values
BIt forces the program to crash on error
CIt ignores errors silently and returns a default value
DIt throws errors without catching them
If a function returns String, what type does try? return?
AString?
BOptional<String>
CBoth A and C
DString
What happens if you use try! and the function throws an error?
AThe program crashes
BIt returns nil
CIt returns an optional
DIt ignores the error
Which keyword safely handles errors by returning an optional?
Acatch
Btry?
Ctry
Dtry!
Explain how try? works in Swift and when you might use it.
Think about how to avoid crashes but still get a result or nil.
You got /4 concepts.
    Compare try? and try! in Swift. What are the risks and benefits of each?
    Consider what happens when an error is thrown.
    You got /4 concepts.