0

Recently I am doing some code tests and found that fixed-size array creation is not as simple in Swift compare to other languages, say c++.

I have seen the solution for 1d array here : link:

One Dimension array, compare c++ with Swift:

// In c++

int array1[64];    // 1-dimension array size 64

// In Swift

var array1 = [Int?](repeating: nil, count: 64) // 1 dimension array size 64

For 2-dimension array:

// in c++

int array2[64][64]; // 2-dimension array size 64x64

// in Swift

var array2 : [[Int?]] = ???????

How to initiate a fixed-size 2d array in swift?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Marco Leong
  • 565
  • 4
  • 11

1 Answers1

2

I found the answer by testing it out in Playground, here's the solution:

In c++

int array1[64];    // 1-dimension array size 64

int array2[64][64]; // 2-dimension array size 64x64

in Swift:

var array1 = [Int?](repeating: nil, count: 64) // 1 dimension array

var array2 = [[Int?]](
 repeating: [Int?](repeating: nil, count: 64)
 count: 64
) // 2-dimension array size 64x64

// Access it like normal

array2[4][2] = 42
print(array2[4][2]) // output: 42

A bonus, 3-dimension array in swift !!!

var array3 = 
[[[Int?]]](
  repeating: [[Int?]](
    repeating: [Int?](
      repeating: nil,
      count: 3),
  count: 3),
count: 3)
Marco Leong
  • 565
  • 4
  • 11