VOOZH about

URL: https://www.geeksforgeeks.org/swift/swift-how-to-store-values-in-arrays/

⇱ Swift - How to Store Values in Arrays? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Swift - How to Store Values in Arrays?

Last Updated : 23 Nov, 2021

An array is a collection of elements having a similar data type. Normally to store a value of a particular data type we use variables. Now suppose we want to store marks of 5 students of a class. We can create 5 variables and assign marks to each of them. But for a class having 50 or more students, creating these many variables doesn't look good. Moreover, this practice should be avoided as it makes our source code less readable. To store a large number of elements of similar data types, we can use arrays. Elements can be accessed using index numbers in an array. In Swift, indexing starts with 0. In this article, we will see different methods to store values in an array using Swift programming language.

By Initializing an Array

We can store elements in the array directly at the time of initialization. 

Syntax:

var myArray : [data_type] = [val1, val2, val3,...]

Here, myArray is the array we want to create, data_type is the data type of elements, and val1, val2,.. are the elements we want to store in the array 

Example 1:

Output:

Array1: [1, 3, 5, 7]
Array2: ["G", "e", "e", "k"]

Example 2:

Output:

Array1: [1.2, 5.32, 5.56, 7.15]
Array2: ["Geeks", "for", "Geeks"]

Using append() method

We can also initialize the array using the append() method. This method is used to add an element at the end of the given array.

Syntax:

myArray.append(value)

Here, myArray is the array that we have created and value is the element we want to add at the end of the array

Example 1:

Output:

Array1: [1, 3, 5, 7]
Array2: ["G", "e", "e", "k"]

Example 2:

Output:

Array 1 is: [1.2, 5.32, 5.56]
Array 2 is: [2.9, 4.5, 2.0]
Final Array: [2.9, 4.5, 2.0, 1.2, 5.32, 5.56]

Using insert() method

We can also initialize the array using the insert() method. This method is used to add elements at a given position of the array.

Syntax:

myArray.insert(value, at : index)

Here, myArray is the array that we have created, value is the element we want to add and index is the index at which we want to add the element 

Example 1:

Output:

Array1: [1, 3, 5, 7]
Array2: ["G", "e", "e", "k"]

Example 2:

Output:

Array1: [1.2, 5.32, 5.56, 7.15]
Array2: ["Geeks", "for", "Geeks"]
Comment
Article Tags:
Article Tags:

Explore