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
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.
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.
Swift Array append() The append() method adds a new element at the end of the array.
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())
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With