Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Swift empty two dimensional array with size

Tags:

arrays

swift

I try to do smth like this:

let myArray: [[MyClass]] = [5,5]

where [5,5] is size of array. I can't do this.

like image 886
mriddi Avatar asked Jul 17 '14 18:07

mriddi


People also ask

How do you initialize a 2D array size?

On the other hand, to initialize a 2D array, you just need two nested loops. 6) In a two dimensional array like int[][] numbers = new int[3][2], there are three rows and two columns. You can also visualize it like a 3 integer arrays of length 2.

How do you declare an empty array in Swift?

To create an empty string array in Swift, specify the element type String for the array and assign an empty array to the String array variable.


2 Answers

If you want to make a multidimensional array of value types (i.e. Ints, Strings, structs), the syntax in codester's answer works great:

Swift 4

var arr = [[Int]](repeating: [Int](repeating: 0, count: 5), count: 5)

Swift Earlier

var arr = [[Int]](count: 5, repeatedValue: [Int](count: 5, repeatedValue: 0))
arr[0][1] = 1
// arr is [[0, 1, 0, 0, 0], ...

If you make a multidimensional array of reference types (i.e. classes), this gets you an array of many references to the same object:

class C {
    var v: Int = 0
}
var cArr = [[C]](count: 5, repeatedValue: [C](count: 5, repeatedValue: C()))
// cArr is [[{v 0}, {v 0}, {v 0}, {v 0}, {v 0}], ...
cArr[0][1].v = 1
// cArr is [[{v 1}, {v 1}, {v 1}, {v 1}, {v 1}], ...

If you want to make an array (uni- or multidimensional) of reference types, you might be better off either making the array dynamically:

var cArr = [[C]]()
for _ in 0..<5 {
    var tmp = [C]()
    for _ in 0..<5 {
        tmp += C()
    }
    cArr += tmp
}
// cArr is [[{v 0}, {v 0}, {v 0}, {v 0}, {v 0}], ...
cArr[0][1].v = 1
// cArr is [[{v 0}, {v 1}, {v 0}, {v 0}, {v 0}], ...

(See slazyk's answer for equivalent shorter syntax using map().)

Or making an array of optionals and filling in their values:

var optArr = [[C?]](count: 5, repeatedValue: [C?](count: 5, repeatedValue: nil))
// optArr is [[nil, nil, nil, nil, nil], ...
optArr[0][1] = C()
// optArr is [[nil, {v 0}, nil, nil, nil], ...
like image 115
rickster Avatar answered Oct 20 '22 10:10

rickster


Creating 5x5 array filled with distinct objects of the same class. Maybe not the prettiest solution, but a working one, and avoiding the for loops:

let myArray = [[MyClass]](map(0..<5) { _ in
    [MyClass](map(0..<5) { _ in
        MyClass()
    })
})

Edit:
Since the question was actually to create 'empty' array with 'size', I'd have to add that you cannot have it 'empty' if it is not of an optional type. But if that is what you want, you can also do it as rickster suggests at the bottom of his answer and just create 5x5 array of nil.

like image 31
slazyk Avatar answered Oct 20 '22 11:10

slazyk