1

I'm working on a tic tac toe app, and I have 9 buttons (3x3). I want to makea 2d array of all the buttons and put in all the solutions. How can I implement a 2d array?

frosty
  • 63
  • 1
  • 9

2 Answers2

3

A 2D array is just an array of arrays.

// this will create an empty array
let buttons = [[UIButton]]()

or...

let buttons = [
    [button1, button2, button3],
    [button4, button5, button6],
    [button7, button8, button9]
]

There are many ways to do this.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
0

use this

class Utils{

    static func arrayToArrays<T>(arr: Array<T>,size: Int)->Array<Array<T>>{

        var result : Array<Array<T>> = Array<Array<T>>(count: size, repeatedValue: Array<T>());
        var set = -1;
        var expectedSize = (arr.count / size) + (arr.count % size);

        for i in 0..<arr.count {
            if i % expectedSize == 0{
                set++;
            }

            result[set].append(arr[i]);
        }

        return result;
    }
}

use:

var my1DArray = [1,2,3,4,5,6,7,8,9];
var my2DArray = Utils.arrayToArrays(my1DArray,size:3); //[[1,2,3],[4,5,6],[7,8,9]]
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44