How to create Swift empty two dimensional array with size

前端 未结 5 1586

I try to do smth like this:

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

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

5条回答
  •  [愿得一人]
    2020-12-28 19:34

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

提交回复
热议问题