Bird
0
0

Which of the following correctly creates and initializes an array of optional Integers with 1, nil, and 3 in Swift?

hard📝 Application Q8 of 15
Swift - Collections
Which of the following correctly creates and initializes an array of optional Integers with 1, nil, and 3 in Swift?
Avar numbers: [Int] = [1, nil, 3]
Bvar numbers: [Optional<Int>] = [1, 2, 3]
Cvar numbers: [Int?] = [1, nil, 3]
Dvar numbers = [Int?]()
Step-by-Step Solution
Solution:
  1. Step 1: Understand optional array element type

    To hold nil values, array elements must be optional Ints, written as Int?.
  2. Step 2: Check array initialization

    var numbers: [Int?] = [1, nil, 3] correctly declares an array of optional Ints with a nil value inside. var numbers: [Int] = [1, nil, 3] is invalid because non-optional Int array cannot hold nil. var numbers: [Optional] = [1, 2, 3] is valid syntax but does not include nil. var numbers = [Int?]() creates an empty optional Int array but does not initialize with values.
  3. Final Answer:

    var numbers: [Int?] = [1, nil, 3] -> Option B
  4. Quick Check:

    Optional element array with nil = var numbers: [Int?] = [1, nil, 3] [OK]
Quick Trick: Use [Int?] to allow nil in array elements [OK]
Common Mistakes:
  • Using non-optional Int array with nil
  • Confusing Optional syntax
  • Not initializing array with nil values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes