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

查看:82
本文介绍了Swift 3 2D Int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实际上是一个非常简单的问题,但是一个小时后我无法解决我的问题。

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

我需要创建一个二维Int数组。

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]] = []

创建类型为 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.

让我们退回到一个数组:

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

首先必须在数组中添加7个值,然后才能访问索引 6 处的值(第七个值)。

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 2D Int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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