Swift 3 二维 Int 数组 [英] Swift 3 2d array of Int

查看:41
本文介绍了Swift 3 二维 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]] = []

尝试更改值:

arr[x][y] = 1

致命错误:索引超出范围

fatal error: Index out of range

我应该使用 APPEND 还是需要指定数组的大小?

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

我很困惑..

推荐答案

其实并不简单.行:

var arr : [[Int]] = []

创建一个 Array of Int 类型的变量,并且最初该数组为空.您需要像 Swift 中的任何其他数组一样填充它.

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.

让我们回到单个数组:

var row : [Int] = []

您现在有一个空数组.你不能只做:

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

row[6] = 10

您首先必须向数组添加 7 个值,然后才能访问索引 6 处的值(第 7 个值).

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.

假设您想要一个每个值都设置为 0 的预填充矩阵,这是一种初始化数组的简单方法.

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

这篇关于Swift 3 二维 Int 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆