Init多维数组

时间:2015-03-15 14:13:15

标签: arrays swift initialization

只是一个小捷径问题。

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

将初始化一维数组。有没有办法为二维数组做到这一点?长形式将是:

var gradesTimeline = [[Int]]()
for i in 0...10 { gradesTimeline.append(gradeTimeline) }

1 个答案:

答案 0 :(得分:1)

尝试:

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
  }
}