📖 Scenario: Imagine you are writing a simple Swift program that reads a number from a string and you are sure the string always contains a valid number. You want to convert the string to an integer using try! to force unwrap the result.
🎯 Goal: You will create a string containing a number, then use try! to convert it to an integer, and finally print the integer.
📋 What You'll Learn
Create a string variable called numberString with the value "123".
Create a function called convertToInt that takes a String and returns an Int, and throws an error if conversion fails.
Use try! to call convertToInt with numberString and assign the result to a variable called number.
Print the value of number.
💡 Why This Matters
🌍 Real World
In real apps, you often convert strings to numbers. Using <code>try!</code> is a quick way to unwrap when you are sure the conversion will succeed.
💼 Career
Understanding error handling and forced unwrapping is important for Swift developers to write safe and efficient code.
Progress0 / 4 steps
1
Create the string variable
Create a string variable called numberString and set it to the value "123".
Swift
Hint
Use let numberString = "123" to create the string.
2
Create the conversion function
Create a function called convertToInt that takes a String parameter called input and returns an Int. The function should throw an error if the string cannot be converted to an integer. Use Int(input) and throw a generic error if conversion fails.
Swift
Hint
Use if let to unwrap Int(input). Throw an error if it is nil.
3
Use try! to convert the string
Use try! to call convertToInt with numberString and assign the result to a variable called number.
Swift
Hint
Use let number = try! convertToInt(input: numberString) to force unwrap the result.
4
Print the converted number
Print the value of the variable number.
Swift
Hint
Use print(number) to show the result.
Practice
(1/5)
1. What does try! do in Swift when calling a function that can throw an error?
easy
A. It catches errors and handles them gracefully.
B. It converts the error into a warning message.
C. It ignores the function and returns nil.
D. It runs the function and forces the result without catching errors.
Solution
Step 1: Understand the role of try!
try! runs a throwing function but does not catch errors.
Step 2: Recognize the behavior on error
If an error occurs, the program crashes instead of handling it.
Final Answer:
It runs the function and forces the result without catching errors. -> Option D
Quick Check:
try! forces result without error handling [OK]
Hint: Remember: try! crashes on error, no catch block used [OK]
Common Mistakes:
Thinking try! catches errors
Assuming try! returns nil on error
Confusing try! with try?
2. Which of the following is the correct syntax to use try! with a throwing function named loadData()?
easy
A. let data = try! loadData()
B. let data = try loadData()
C. let data = try? loadData()
D. let data = loadData()!
Solution
Step 1: Recall correct try! syntax
The forced try syntax is try! followed by the function call.
Step 2: Match syntax to options
let data = try! loadData() uses try! correctly before loadData().
Final Answer:
let data = try! loadData() -> Option A
Quick Check:
Correct forced try syntax = let data = try! loadData() [OK]
Hint: Use try! directly before the function call without parentheses [OK]
Common Mistakes:
Using try without ! for forced unwrap
Using try? which returns optional
Adding ! after function call incorrectly
3. Consider this Swift code:
func getNumber() throws -> Int {
return 42
}
let result = try! getNumber()
print(result)
What will be the output when this code runs?
medium
A. nil
B. 42
C. Runtime error
D. Compilation error
Solution
Step 1: Analyze the throwing function
getNumber() always returns 42 and does not throw an error.
Step 2: Understand try! behavior here
Since no error occurs, try! unwraps the result safely.
Final Answer:
42 -> Option B
Quick Check:
No error thrown, so output is 42 [OK]
Hint: If no error thrown, try! returns value directly [OK]
Common Mistakes:
Expecting runtime error even if no error thrown
Thinking try! returns optional
Confusing with try? behavior
4. What is the problem with this Swift code?
func fail() throws -> String {
throw NSError(domain: "Error", code: 1)
}
let text = try! fail()
print(text)
medium
A. It causes a runtime crash due to forced unwrap of error.
B. It compiles but prints an empty string.
C. It returns nil without crashing.
D. It causes a compile-time error.
Solution
Step 1: Identify the throwing function behavior
fail() always throws an error when called.
Step 2: Understand try! effect on error
try! forces unwrap and crashes if an error is thrown.
Final Answer:
It causes a runtime crash due to forced unwrap of error. -> Option A
Quick Check:
try! crashes on thrown error [OK]
Hint: try! crashes if error thrown, no catch block used [OK]
Common Mistakes:
Expecting graceful error handling
Thinking it returns nil on error
Assuming compile-time error
5. You have a function that reads a configuration file and throws an error if the file is missing: