Multidimensional Arrays from C to Swift

In C I have the following multidimensional array:

unsigned wins[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};

      

I use the following code to access the elements:

int i;
for(i = 0; i < 8; ++i)     {
    unsigned *positions;
    positions = wins[i];

    unsigned pos0 = positions[0];
    unsigned pos1 = positions[1];
    unsigned pos2 = positions[2];

    if(arrayPassedIn[pos0] != 0 && arrayPassedIn[pos0] == arrayPassedIn[pos1] && arrayPassedIn[pos0] == arrayPassedIn[pos2])
    {
         // Do Something Here
    }

      

I know quickly, I can do something like:

var array = Array<Array<Int>>()

      

But I'm not sure if this gives the same result for accessing elements.

+3


source to share


2 answers


You can create a multidimensional matrix in a pretty similar way to your C code:

var wins = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]

      

Swift code is used the same way your C code is also very similar; the main difference is using a for-in loop instead of a standard loop for

(although you can do that too).



for positions in wins {
    var pos0 = positions[0]
    var pos1 = positions[1]
    var pos2 = positions[2]

    if(arrayPassedIn[pos0] != 0 && arrayPassedIn[pos0] == arrayPassedIn[pos1] && arrayPassedIn[pos0] == arrayPassedIn[pos2])
    {
        // Do Something Here
    }
}

      

Note that while there are similarities, arrays in Swift are not , for example arrays in C. For example, when you iterate over wins

, you are actually making copies of the arrays positions

(the actual memory copy only happens if you write the array, so actually no performance penalty). If you then set, say, a positions[0]

different value, that value will not be updated in wins

as if it were C.

+3


source


I've never worked in obj-C, but in swift I think the equivalent is:



let array: [(Int, Int, Int)] = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
println(array[2].0) //6

      

+1


source







All Articles