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:
Step 1: Understand optional array element type
To hold nil values, array elements must be optional Ints, written as Int?.
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.
Final Answer:
var numbers: [Int?] = [1, nil, 3] -> Option B
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
Master "Collections" in Swift
9 interactive learning modes - each teaches the same concept differently