Reputation: 10744
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}};
To access the elements I use the following code:
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 in swift I can do something like:
var array = Array<Array<Int>>()
But I'm not sure if this produces the same result for accessing the elements.
Upvotes: 3
Views: 203
Reputation: 42325
You can create a multi-dimentsional array in a pretty similar manner 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]]
The Swift code to use it the same way as your C code is also pretty similar; the main difference is using a for-in loop instead of the standard for
loop (although you could 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
}
}
Do note that, even though there are similarities, Arrays in Swift are not like arrays in C. For instance, when you're looping over wins
, you're actually creating copies of the positions
arrays (the actual memory copy only happens if you write to the array, so there's not really a performance penalty). If you then set, say, positions[0]
to a different value, that value would not be updated in wins
like it would if this were C.
Upvotes: 3
Reputation: 19524
I have 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
Upvotes: 1