Init multi-dimensional array

qwerty_so

Just a little shortcut issue.

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

will init a one-dimenstional array. Is there a way to do that for a 2-dimensional array too? Long form would be:

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

Try:

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

But, because of the value semantics of Array you can also do:

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

which results in

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related