📖 Scenario: Imagine you are creating a simple contact app. Sometimes, a contact might have a middle name, but sometimes they might not. You want to store this information safely without causing errors.
🎯 Goal: You will create a Swift program that uses optional declaration with the ? suffix to handle a contact's middle name, which might or might not be present.
📋 What You'll Learn
Create a variable called middleName declared as an optional String?
Assign nil to middleName initially
Assign a real middle name string to middleName
Use optional binding with if let to safely unwrap and print the middle name
Print a message if the middle name is not available
💡 Why This Matters
🌍 Real World
Optional variables are useful when some information might be missing, like a middle name or a phone number in a contact app.
💼 Career
Understanding optionals is essential for Swift developers to write safe code that avoids crashes from missing values.
Progress0 / 4 steps
1
Declare an optional variable with ? suffix
Create a variable called middleName of type String? and set it to nil.
Swift
Hint
Use var middleName: String? = nil to declare an optional string variable that starts empty.
2
Assign a value to the optional variable
Assign the string "James" to the variable middleName.
Swift
Hint
Just write middleName = "James" to give the optional a real value.
3
Use optional binding to safely unwrap
Use if let with a constant called name to unwrap middleName and print "Middle name is: \(name)" inside the block.
Swift
Hint
Use if let name = middleName { ... } to safely check if middleName has a value.
4
Add else to handle nil case and print result
Add an else block to the if let statement that prints "No middle name provided" when middleName is nil. Run the program to see the output.
Swift
Hint
Use else { print("No middle name provided") } to handle the case when middleName is nil.
Practice
(1/5)
1. What does adding a ? after a type in Swift mean?
easy
A. The variable can hold a value or be nil (missing).
B. The variable is a constant and cannot change.
C. The variable must always have a value.
D. The variable is an array of that type.
Solution
Step 1: Understand the meaning of ? in Swift type declaration
In Swift, adding ? after a type means the variable is optional and can hold either a value or nil.
Step 2: Compare with other options
Other options describe constants, non-optional variables, or arrays, which are unrelated to the ? suffix.
Final Answer:
The variable can hold a value or be nil (missing). -> Option A
Quick Check:
Optional type = value or nil [OK]
Hint: Remember: ? means value can be missing [OK]
Common Mistakes:
Thinking ? makes a constant
Confusing optional with array type
Assuming optional must always have a value
2. Which of these is the correct way to declare an optional integer in Swift?
easy
A. var number: Int?
B. var number: ?Int
C. var number: Int!
D. var number: OptionalInt
Solution
Step 1: Recall Swift syntax for optional declaration
In Swift, an optional type is declared by placing ? after the type name, like Int?.
Step 2: Check each option
var number: Int? uses Int? correctly. var number: ?Int places ? before the type, which is invalid. var number: Int! uses ! which is an implicitly unwrapped optional, different from ?. var number: OptionalInt uses a non-existent type OptionalInt.
Final Answer:
var number: Int? -> Option A
Quick Check:
Optional syntax = type followed by ? [OK]
Hint: Put ? right after the type name [OK]
Common Mistakes:
Placing ? before the type
Confusing ? with !
Using non-existent types like OptionalInt
3. What will be the output of this Swift code?
var name: String? = "Alice"
print(name)
medium
A. nil
B. Alice
C. Optional("Alice")
D. Error: Cannot print optional directly
Solution
Step 1: Understand printing an optional variable
When printing an optional variable directly, Swift shows it wrapped as Optional(value) if it has a value.
Step 2: Check the variable value
The variable name holds the string "Alice", so printing it shows Optional("Alice").
The variable age is an optional Int (Int?), but adding it directly to an Int (5) is not allowed without unwrapping.
Step 2: Understand Swift's type safety
Swift requires unwrapping optionals before using them in arithmetic operations to avoid runtime errors.
Final Answer:
Cannot add Int? and Int directly. -> Option D
Quick Check:
Optional must be unwrapped before arithmetic [OK]
Hint: Unwrap optionals before arithmetic operations [OK]
Common Mistakes:
Trying to add optional and non-optional directly
Ignoring need to unwrap optionals
Thinking semicolons are required in Swift
5. Given this Swift code, how can you safely print the length of the optional string text?
var text: String? = "Hello"
// Your code here
hard
A. print(text ?? 0)
B. if let safeText = text { print(safeText.count) } else { print(0) }
C. print(text!)
D. print(text.count)
Solution
Step 1: Understand optional unwrapping with if let
Using if let safely unwraps the optional text only if it has a value, avoiding crashes.
Step 2: Use unwrapped value to get length
Inside the if let block, safeText.count gives the length. If text is nil, print 0.
Step 3: Check other options
print(text.count) tries to access count on optional directly (error). print(text!) force unwraps without check (unsafe). print(text ?? 0) uses nil coalescing but mismatches types.
Final Answer:
if let safeText = text { print(safeText.count) } else { print(0) } -> Option B
Quick Check:
Use if let to safely unwrap optionals [OK]
Hint: Use if let to unwrap optionals safely [OK]
Common Mistakes:
Forcing unwrap without checking nil
Accessing properties on optional without unwrapping
Using nil coalescing with wrong types
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.