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
219 views
in Technique[技术] by (71.8m points)

Swift 3 2d array of Int

It's actually a very simple question, but after an hour I can not solve my problem.

I need to create a 2d array of Int.

var arr = [[Int]]()
or
var arr : [[Int]] = []

tried to change value :

arr[x][y] = 1

fatal error: Index out of range

Should I use APPEND or I need specify the size of the array?

I'm confused..

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It's not simple really. The line:

var arr : [[Int]] = []

Creates a variable of type Array of Array of Int and initially the array is empty. You need to populate this like any other other array in Swift.

Let's step back to a single array:

var row : [Int] = []

You now have an empty array. You can't just do:

row[6] = 10

You first have to add 7 values to the array before you can access the value at index 6 (the 7th value).

With your array of arrays, you need to fill in the outer array with a whole set of inner arrays. And each of those inner arrays need to be filled out with the proper number of values.

Here is one simple way to initialize your array of arrays assuming you want a pre-filled matrix with every value set to 0.

var matrix : [[Int]] = Array(repeating: Array(repeating: 0, count: 10), count: 10)

The outer count represents the number of rows and the inner count represents the number of columns. Adjust each as needed.

Now you can access any cell in the matrix:

matrix[x][y] = 1 // where x and y are from 0 to rows-1/columns-1

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

...