只是一个捷径问题。

let history = 5
var gradeTimeline = [Int](count:history*12, repeatedValue:0)

将初始化一维数组。是否也可以对二维数组执行此操作?长格式为:
var gradesTimeline = [[Int]]()
for i in 0...10 { gradesTimeline.append(gradeTimeline) }

最佳答案

尝试:

var gradesTimeline = (0..<10).map { _ in [Int](count:12*history, repeatedValue:0) }


但是,由于Array的值语义,您还可以执行以下操作:

var gradesTimeline = [[Int]](count:2, repeatedValue:([Int](count:3, repeatedValue:0)))


导致

gradesTimeline: [[Int]] = 2 values {
  [0] = 3 values {
    [0] = 0
    [1] = 0
    [2] = 0
  }
  [1] = 3 values {
    [0] = 0
    [1] = 0
    [2] = 0
  }
}
 18> gradesTimeline[0][0]=10
 19> gradesTimeline[1][2]=20
 20> gradesTimeline
$R4: [[Int]] = 2 values {
  [0] = 3 values {
    [0] = 10
    [1] = 0
    [2] = 0
  }
  [1] = 3 values {
    [0] = 0
    [1] = 0
    [2] = 20
  }
}

关于arrays - 初始化多维数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29061594/

10-09 05:56