Bird
Raised Fist0
Swiftprogramming~20 mins

Optional declaration with ? suffix in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Optional Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code with optional?
Consider the following Swift code. What will be printed when it runs?
Swift
var name: String? = "Alice"
print(name)
AOptional("Alice")
BAlice
Cnil
DError: Variable 'name' not initialized
Attempts:
2 left
💡 Hint
Remember that printing an optional variable shows it wrapped in Optional(...) if it has a value.
❓ Predict Output
intermediate
2:00remaining
What is the value of 'age' after this code runs?
Look at this Swift code snippet. What is the value of 'age' after execution?
Swift
var age: Int? = nil
age = 30
AOptional(30)
Bnil
C30
DError: Cannot assign non-optional to optional
Attempts:
2 left
💡 Hint
Assigning a non-optional value to an optional variable wraps it automatically.
❓ Predict Output
advanced
2:00remaining
What error does this code produce?
What error will this Swift code cause when compiled?
Swift
var score: Int? = 10
var total: Int = score + 5
ASyntax error: Missing optional unwrapping
BNo error, total is 15
CRuntime error: nil value unwrapped
DType error: Cannot add 'Int?' and 'Int'
Attempts:
2 left
💡 Hint
You cannot directly add an optional Int and a non-optional Int without unwrapping.
🧠 Conceptual
advanced
2:00remaining
Which statement about optional declaration with '?' is true?
Choose the correct statement about declaring variables with '?' in Swift.
AVariables with '?' cannot be assigned nil after initialization.
BA variable declared with '?' must always have a value assigned.
CA variable declared with '?' can hold a value or nil.
DUsing '?' means the variable is a constant and cannot change.
Attempts:
2 left
💡 Hint
Think about what '?' means in Swift variable declarations.
❓ Predict Output
expert
3:00remaining
What is the output of this Swift optional chaining code?
Analyze the code and select the output printed.
Swift
class Person {
    var pet: Pet?
}

class Pet {
    var name: String
    init(name: String) { self.name = name }
}

let person = Person()
print(person.pet?.name ?? "No pet")
AOptional(nil)
BNo pet
Cnil
DRuntime error: Unexpected nil
Attempts:
2 left
💡 Hint
Optional chaining returns nil if any part is nil, and the nil-coalescing operator provides a default.

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

  1. 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.
  2. Step 2: Compare with other options

    Other options describe constants, non-optional variables, or arrays, which are unrelated to the ? suffix.
  3. Final Answer:

    The variable can hold a value or be nil (missing). -> Option A
  4. 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

  1. Step 1: Recall Swift syntax for optional declaration

    In Swift, an optional type is declared by placing ? after the type name, like Int?.
  2. 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.
  3. Final Answer:

    var number: Int? -> Option A
  4. 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

  1. 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.
  2. Step 2: Check the variable value

    The variable name holds the string "Alice", so printing it shows Optional("Alice").
  3. Final Answer:

    Optional("Alice") -> Option C
  4. Quick Check:

    Printing optional shows Optional(value) [OK]
Hint: Printing optional shows Optional(...) wrapper [OK]
Common Mistakes:
  • Expecting direct value without Optional()
  • Assuming printing optional causes error
  • Confusing nil with a string value
4. Identify the error in this Swift code:
var age: Int?
age = 25
print(age + 5)
medium
A. Variable age is not initialized.
B. Optional variables cannot be printed.
C. Missing semicolon after age = 25.
D. Cannot add Int? and Int directly.

Solution

  1. Step 1: Analyze the operation on optional and Int

    The variable age is an optional Int (Int?), but adding it directly to an Int (5) is not allowed without unwrapping.
  2. Step 2: Understand Swift's type safety

    Swift requires unwrapping optionals before using them in arithmetic operations to avoid runtime errors.
  3. Final Answer:

    Cannot add Int? and Int directly. -> Option D
  4. 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

  1. Step 1: Understand optional unwrapping with if let

    Using if let safely unwraps the optional text only if it has a value, avoiding crashes.
  2. Step 2: Use unwrapped value to get length

    Inside the if let block, safeText.count gives the length. If text is nil, print 0.
  3. 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.
  4. Final Answer:

    if let safeText = text { print(safeText.count) } else { print(0) } -> Option B
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard