Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add value to empty Swift array

Tags:

arrays

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[]()

and

var emptyArray = []

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

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!

like image 516
Fried Rice Avatar asked Jun 15 '14 11:06

Fried Rice


1 Answers

First, create empty Int array:

var emptyArray : Int[] = []

or:

var emptyArray = Int[]()

Add number to that array (two ways):

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

Array now contains [1, 2]

like image 189
juniperi Avatar answered Oct 04 '22 00:10

juniperi