Swift – Initialize 2D Array

To initialize a 2D array with values in Swift, assign the variable with an array whose elements are arrays. Each inner-array can contain any number of elements of any type.

Example

In the following example, we will initialize a 2D array with integer values.

main.swift

</>
Copy
var arr = [ [4, 5, 8],
            [1, 9, 6],
            [2, 3, 7] ]

print(arr)

Output

Swift - Initialize 2D Array

Inner arrays can be of any size. Let us initialize an array with inner arrays of different sizes.

main.swift

</>
Copy
var arr = [ [4, 5, 8],
            [1, 9, 6, 74, 99],
            [2, 3] ]

print(arr)

Output

Swift - Initialize 2D Array - Different Sizes for Inner Arrays

Conclusion

In this Swift Tutorial, we learned how to initialize a two dimensional Swift Array.