Search code examples
swiftmultidimensional-arrayoption-typeuint16

How to create 3D array of optionals w/ set size


How would I go about creating a 3-dimensional array of UInt16? with a set size where each element is by default set to nil?

My attempt was

var courseInfo = UInt16?(count:10, repeatedValue: UInt16?(count:10, repeatedValue: UInt16?(count:10, repeatedValue:nil)))

although that doesn't seem to work. Any ideas?


Solution

  • Your code errored because you weren't creating arrays, you were mixing them up with UInt16?s.

    Let's start at the base case, how do you make a one-dimensional array?

    Array<UInt16?>(count: 10, repeatedValue: nil)
    

    What if we wanted a two dimensional array? Well, now we are no longer initializing an Array<UInt16?> we are initializing an Array of Arrays of UInt16?, where each sub-array is initialized with UInt16?s.

    Array<Array<UInt16?>>(count:10, repeatedValue: Array<UInt16?>(count:10, repeatedValue:nil))
    

    Repeating this for the 3-dimensional case just requires more of the same ugly nesting:

    var courseInfo = Array<Array<Array<UInt16?>>>(count:10, repeatedValue: Array<Array<UInt16?>>(count:10, repeatedValue: Array<UInt16?>(count:10, repeatedValue:nil)))
    

    I'm not sure if this is the best way to do it, or to model a 3D structure, but this is the closest thing to your code right now.

    EDIT:

    Martin in the comments pointed out that a neater solution is

    var courseInfo : [[[UInt16?]]] = Array(count: 10, repeatedValue: Array(count : 10, repeatedValue: Array(count: 10, repeatedValue: nil)))
    

    Which works by moving the type declaration out front, making the repeatedValue: parameter unambiguous.