Add value to an empty Swift array

I cannot figure out how to add values ​​to an empty array in Swift. I tried to start with an 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 tried adding an integer to the array with emptyArray.append(1), emptyArray += [1]but none of them work and it is not in the directory (or maybe it is hidden where I could not understand). Both of them work if it has one or more meanings, and it drives me crazy! Please let me know how to do this if you know how to do it. Thank!

+4
source share
3 answers

First create an empty Int array:

var emptyArray : Int[] = []

or

var emptyArray = Int[]()

( ):

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

[1, 2]

+14

Swift :

 var emptyArray = [Int]()

/, :

emptyArray.append(6)

, , , , . , , Int.

XCode - .

+3

     var arrName = [String]()
     arrName = ["Deep", "Hemant", "Yash"]
     print("old array--> ", arrName)
     arrName.append("Jay")
     print("new array--> ", arrName)

: - old array--> ["Deep", "Hemant", "Yash"]

new array--> ["Deep", "Hemant", "Yash", "Jay"]

0

Source: https://habr.com/ru/post/1544641/


All Articles