Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create arraylist of object in swift

Tags:

arrays

swift

In java, we can create arraylist of object like this:

ArrayList<Country> countryList = new ArrayList<Country>();          Country aBucket = new Country();         aBucket.setName("Canada");         aBucket.setCity("Ottawa");         countryList.add(aBucket); 

or like this way:

ArrayList<Matrices> list = new ArrayList<Matrices>(); list.add( new Matrices(1,1,10) ); list.add( new Matrices(1,2,20) ); 

But how can I get the same things/alternative in SWIFT

like image 474
Asim Roy Avatar asked Nov 24 '15 11:11

Asim Roy


People also ask

How do I create an array in Swift 5?

It is important to note that, while creating an empty array, we must specify the data type inside the square bracket [] followed by an initializer syntax () . Here, [Int]() specifies that the empty array can only store integer data elements. Note: In Swift, we can create arrays of any data type like Int , String , etc.

How do you create an array of strings in Swift?

Swift makes it easy to create arrays in your code using an array literal: simply surround a comma-separated list of values with square brackets. Without any other information, Swift creates an array that includes the specified values, automatically inferring the array's Element type.

How do you add to an array in Swift?

Swift Array append() The append() method adds a new element at the end of the array.


2 Answers

You can do this using an Array. Take a look here for more information about arrays.

You can use the append(...) function to add objects.

var array = [Country]() //alternatively (does the same): var array = Array<Country>() array.append(Country()) array.append(Country()) 
like image 91
mad_manny Avatar answered Sep 29 '22 04:09

mad_manny


Trying to make the code as close to your example code, this is my answer (requires to have declared Country class somewhere:

var countryList : Array<Country> = Array() var aBucket     : Country        = Country() .... countryList.append(aBucket) 

Hope this helps

like image 24
LukeSideWalker Avatar answered Sep 29 '22 04:09

LukeSideWalker