Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

Multidimensional arrays in Swift

Edit: As Adam Washington points out, as from Beta 6, this code works as is, so the question is no longer relevant.

I am trying to create and iterate through a two dimensional array:

var array = Array(count:NumColumns, repeatedValue:Array(count:NumRows, repeatedValue:Double()))

array[0][0] = 1
array[1][0] = 2
array[2][0] = 3
array[0][1] = 4
array[1][1] = 5
array[2][1] = 6
array[0][2] = 7
array[1][2] = 8
array[2][2] = 9

for column in 0...2 {
    for row in 0...2 {
        println("column: (column) row: (row) value:(array[column][row])")
    }
}

However, this is the output I get:

column: 0 row: 0 value:3.0
column: 0 row: 1 value:6.0
column: 0 row: 2 value:9.0
column: 1 row: 0 value:3.0
column: 1 row: 1 value:6.0
column: 1 row: 2 value:9.0
column: 2 row: 0 value:3.0
column: 2 row: 1 value:6.0
column: 2 row: 2 value:9.0

It looks as if the last column in the row is overwriting the other column values.

Am I declaring it wrong?

Edit: Perhaps a picture from the Playground would help:

Captured from Playground

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As stated by the other answers, you are adding the same array of rows to each column. To create a multidimensional array you must use a loop

var NumColumns = 27
var NumRows = 52
var array = Array<Array<Double>>()
for column in 0..NumColumns {
    array.append(Array(count:NumRows, repeatedValue:Double()))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...