I try to do smth like this:
let myArray: [[MyClass]] = [5,5]
where [5,5] is size of array. I can\'t do this.
If you want to make a multidimensional array of value types (i.e. Int
s, String
s, 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], ...