为空的Swift数组添加值 [英] Add value to empty Swift array

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

问题描述

我无法弄清楚如何在Swift中向空数组添加值.我尝试以两种不同的方式开始使用空数组:

I cannot figure out how to add values to an empty array in Swift. I have tried started with empty array in two different ways:

var emptyArray : Int[]?
emptyArray = Int[]()

var emptyArray = []

(顺便说一下,这两种创建空数组的方式有什么区别?)

(by the way, what is the difference with these two ways of creating empty arrays?)

我尝试使用 emptyArray.append(1) emptyArray + = [1] 向该数组添加一个整数,但是没有用,也不在指南中书(或者,可能是隐藏在我不知道的地方).如果其中包含一个或多个值,那么这两种方法都会起作用,这使我发疯!如果您知道该怎么做,请告诉我该怎么做.谢谢!

I have tried to add an integer to the array with emptyArray.append(1), emptyArray += [1] but none works nor it is in the guide book (or maybe, it is hidden some where that I couldn't figure out). Both of these work if there is one or more values in it and this is driving me crazy! Please let me know how to if you know how to do it. Thank you!

推荐答案

首先,创建一个空的Int数组:

First, create empty Int array:

var emptyArray : Int[] = []

或:

var emptyArray = Int[]()

向该数组添加数字(两种方式):

Add number to that array (two ways):

emptyArray += [1]
emptyArray.append(2)

数组现在包含[1、2]

Array now contains [1, 2]

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

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