Swift 3 2d array of Int

前端 未结 2 1909
南旧
南旧 2020-11-30 09:24

It\'s actually a very simple question, but after an hour I can not solve my problem.

I need to create a 2d array of Int.

var arr = [[Int]]()
or
var a         


        
2条回答
  •  臣服心动
    2020-11-30 10:02

    Not only you need to initialize both the array and subarrays before being able to assign any values, but also each array length must be greater than the index position you are trying to set.

    This is because Swift does neither initialize the subarrays for you, neither increments the array length when assigning to an index.

    For instance, the following code will fail:

    var a = [Int]()
    a[0] = 1
    // fatal error: Index out of range
    

    Instead, you can initialize an array with the number of elements you want to hold, filling it with a default value, zero for example:

    var a = Array(repeating: 0, count: 100)
    a[0] = 1
    // a == [1, 0, 0, 0...]
    

    To create an matrix of 100 by 100 initialized to 0 values:

    var a = Array(repeating: Array(repeating: 0, count: 100), count: 100)
    a[0][0] = 1
    

    If you don't want to specify an initial size for your matrix, you can do it this way:

    var a = [[Int]]()
    a.append([])
    a[0].append(1)
    

提交回复
热议问题