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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.