初始化多维数组
Init multi-dimensional array
只是一个小捷径问题。
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
}
}
只是一个小捷径问题。
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
}
}