Swift – Arrays
An array is one of the most powerful data structures in any programming language. It is used to store elements of similar data types. In other words, suppose we want to store a number of values that are of integer type only then in such cases we can use an array of integers, if values are of type float then we can use an array of float. To understand the importance of an array, let us consider an example. Suppose we need to store marks scored by a student of a class then we create a variable of float type that can hold the marks of the student, if we need to store the marks of two students of a class then we can create two variables of float type that can hold the marks of those students. Now what if we say, we need to store the marks of all students of the class and the strength of the class is more than 100 or 200 or even more. Now we can’t create these many variables. To handle such problems we can use an array of float and initialize it with values one by one. This improves the readability of the code. This article focuses upon arrays in Swift.
Array
An array in Swift can hold values of the same type. There is no restriction imposed regarding the uniqueness of elements. In simple words, elements can be repeated any number of times in the array. To deal with a large number of data items of similar types, arrays can be quite useful. An array can be of any data type like string, int, etc. The elements in an array are stored in a specified position and the position is known as the array index. The index of the array is started from 0 which means the first element of the array is stored on position 0, not 1 like as shown in the below image:
We can create an array using the following syntax:
Syntax:
var myArray: [Int] = [10, 20, 30]
or
var myArray = [10, 20, 30]
Here, if we don’t specify the data type the swift will automatically identify the data type according to the assigned value.
Example:
Swift
// Swift program to create an array // Creating an array of type Int var myArray: [ Int ] = [10, 20, 19] var myArray1 = [11, 20, 29] // Displaying array print (myArray) print (myArray) |
Output:
[10, 20, 19] [10, 20, 19]
Empty array
We can create an empty array in Swift by following the below initializer syntax,
Syntax:
var myArray: [dataType] = []
Here, dataType is a type of value stored by myArray. We have explicitly specified that myArray is of type “dataType”. Now, myArray can contain elements of “dataType” only.
Example:
Swift
// Swift program to create empty array // Creating an empty array of type Int var myArray: [ Int ] = [] |
Array with a default value
Swift provides an initializer using which we can create an array of a specified size with all the values being a default value.
Syntax:
var myArray = Array(repeating: “w3wiki”, count: 3)
Here, myArray is of type String and equals to [“w3wiki”,”w3wiki”, “w3wiki”]
Example:
Swift
// Swift program to demonstrate how to // initialize an array with default values // Initializing array var myArray = Array (repeating: "w3wiki" , count : 3) // Print the array print ( "myArray:" , myArray) |
Output:
myArray: ["w3wiki", "w3wiki", "w3wiki"]
Accessing and modifying array elements
As we know in an array the elements are stored on the specified index and the index is known as the array index. The array index starts from 0 so the first element of the array is present at index 0 not 1. So in Swift, we can access the element using the array index with the help of subscript syntax. In subscript syntax, we use the index of the element (that we want to access) within square brackets, just after the name of the array.
Syntax:
array_Name[index_number]
Example:
Swift
// Swift program to access the elements of an array // Creating an array of type Int var myArray: [ Int ] = [10, 20, 19, 29, 45] // Accessing the element of an array // whose array index is 0 print ( "Element at index 0:" , myArray[0]) // Accessing the element of an array // whose array index is 3 print ( "Element at index 3:" , myArray[3]) |
Output:
Element at index 0: 10 Element at index 3: 29
We can modify elements of the array also with the help of subscript-syntax.
Example:
Swift
// Swift program to demonstrate how to // modify values using subscript-syntax var myArray: [ String ] = [ "w3wiki" , "GfG" , "My" , "DS" ] // Modifying values present at the index 0 // and at the index 1 myArray[0] = "Bhuwanesh" myArray[1] = "Nainwal" // Print the array after modification print ( "myArray:" , myArray) |
Output:
myArray: ["Bhuwanesh", "Nainwal", "My", "DS"]
The subscript-syntax tactic can be used to change a range of values of the array, even if the replacement set of values has a different length than the range we are replacing.
Example:
Swift
// Swift program to illustrate how to modify // values using subscript-syntax // Initialize an array of strings var myArray:[ String ] = [ "GeekforBeginner" , "Swift" , "Java" , "C++" ] // Modify values from 1 to 2 and assign values myArray[1...2] = [ "PHP" , "HTML" ] // Modify values from 1 to 3 and assign values myArray[1...3] = [ "C++" , "C#" ] // Print the array print ( "myArray:" , myArray) |
Output:
myArray: ["GeekforBeginner", "C++", "C#"]
Adding Elements to the Array
Array provides a various in-built methods to store elements. Some of the commonly used methods are:
1. Insert() method: To insert values at a specified index in an array we can use the insert() method used with arrays.
Syntax:
myArray.insert(value, at: index)
Example:
In this program, we have initialized an array of strings. Firstly, we have inserted an element at index 2 then we have inserted an element at index 3 using the insert() method.
Swift
// Swift program to demonstrate the working of // insert() method used with arrays // Initializing an array of strings var myArray: [ String ] = [ "Bhuwanesh" , "Nainwal" ] // Insert at the index 2 myArray.insert( "w3wiki" , at:2) // Print the array print ( "myArray:" , myArray) // Insert at the index 3 myArray.insert( "GFG" , at:3) // Print the array print ( "myArray:" , myArray) |
Output:
myArray: ["Bhuwanesh", "Nainwal", "w3wiki"] myArray: ["Bhuwanesh", "Nainwal", "w3wiki", "GFG"]
2. append() method: To add values at the end of an array, we can use the append method. The syntax is given below,
Syntax:
var myArray[int] = []
myArray.append(10) // myArray = [10]
Example:
Swift
// Swift program to demonstrate the working // of append method used with an array // Creating an empty array var myArray: [ String ] = [] // Adding elements // Using append method myArray.append( "w3wiki" ) myArray.append( "GFG" ) myArray.append( "Bhuwanesh" ) myArray.append( "Nainwal" ) // Displaying result print ( "myArray:" , myArray) |
Output:
myArray: ["w3wiki", "GFG", "Bhuwanesh", "Nainwal"]
Concatenating arrays
In Swift, we can concatenate an array. A new array can be created by joining two existing arrays with compatible types with the help of the (+) operator. The swift compiler infers the type of the newly created array from the type of the two arrays being joined together.
Syntax:
myArray1 + myArray2
Example:
Swift
// Swift program to demonstrate the working of // (+) operator used to combine two arrays // Initializing an array of integers var myArray1: [ Int ] = [6, 1, 4] // Initializing another array of integers var myArray2: [ Int ] = [7, 3, 5, 2] // Creating a new array by combining existing arrays var newArray = myArray1 + myArray2 // Print the array print ( "newArray:" , newArray) |
Output:
newArray: [6, 1, 4, 7, 3, 5, 2]
Iterate over an array
Iterating over an array means going over the elements present in the array, one by one. In Swift, we can iterate over the elements in an array with the help of the “for-in” loop. Below is the syntax to iterate over an array,
Syntax:
for element in myArray {
// body
}
Here, the element points to the current element of myArray.
Example:
In this program, we have initialized an array, myArray with string literals. Now we are iterating over myArray. Here, “element” points to the current element of myArray.
Swift
// Swift program to illustrate how to // iterate over the array // Initializing an array var myArray = [ "w3wiki" , "Bhuwanesh" , "Nainwal" ] // Using for-in loop to iterate over array elements for element in myArray{ // Print the current element print (element) } |
Output:
w3wiki Bhuwanesh Nainwal
Counting array elements
In Swift, we can easily count the elements of the array with the help of the count property. This property is used to determine the number of elements present in an array.
Syntax:
myArray.count
Return type: A non-negative integer: The number of elements present in myArray
Example: In this program, we have initialized an array of integers and we are counting the number of elements present in the array using the “count” property.
Swift
// Swift program to demonstrate the working // of count method used with an array // Array var myArray: [ Int ] = [7, 3, 5, 2] // Displaying the total elements of an array // Using count property print ( "Number of elements present in myArray:" , myArray. count ) |
Output:
Number of elements present in myArray: 4
Removing the elements of an array
In Swift, we can easily remove the elements of the array with the help of the remove() method. This method is used to remove an element from a specific position from an array.
Syntax:
myArray.remove(at: index)
Example: In this program, we have initialized an array of strings. We have removed a particular element using the “remove()” method.
Swift
// Swift program to demonstrate the working // of remove method used with arrays // Initializing an array var myArray: [ String ] = [ "Bhuwanesh" , "Nainwal" , "w3wiki" , "Swift" , "Python" , "Java" ] // Print the array print ( "myArray:" , myArray) // Remove the element present at the index 1 myArray.remove(at: 1) // Print the array print ( "myArray:" , myArray) // Remove the element present at the index 3 myArray.remove(at: 3) // Print the array print ( "myArray:" , myArray) |
Output:
myArray: ["Bhuwanesh", "Nainwal", "w3wiki", "Swift", "Python", "Java"] myArray: ["Bhuwanesh", "w3wiki", "Swift", "Python", "Java"] myArray: ["Bhuwanesh", "w3wiki", "Swift", "Java"]
Contact Us