Swift Arrays Tutorial

We offer you a brighter future with industry-ready online courses - Start Now!!

Arrays are one of the collection type data types in Swift. It stores and manages data elements. They are ordered collections of elements. In Swift, the index of arrays starts from 0, so they are zero-indexed.

var arrayExample: [String] = ["DataFlair", "Swift", "Data Types", "Array"]

Array Creation in Swift

We create an array by defining the data type of the elements of the array within squared brackets [], as shown in the given example.

var array: [Int] = [20, 23]

Creating Empty Array

We create an empty array by declaring an array data type variable and assigning empty square brackets.

var emptyArray: [String] = []

We can add values to the array after its declaration.

Creating an Array with default repeating values

Swift provides a unique way to create an array with default repeating values. We make such arrays by giving values to the two parameters in the declaration. The parameters are repeating and counting. The repeating parameter takes the value, and the count parameter takes the number of elements in the array.

var example: [String] = [String](repeating: "DataFlair", count: 4)
print(example)

Output:

[“DataFlair”, “DataFlair”, “DataFlair”, “DataFlair”]

Type Inference

Type inference helps us deduce an array’s data type based on its initial value. We can omit the type annotation during declaration, and Swift will infer the type for us.

var example = ["DataFlair", "Swift"]

For instance, in the above example, Swift will deduce the data type. It will infer the data type of the variable example as an array of strings.

Accessing Array Values

We use indices to access array element values. The index starts from zero in Swift.

var example = ["DataFlair", "Swift", "Collections"]
print("Index 0:", example[0])
print("Index 1:", example[1])
print("Index 2:", example[2])

Output:

Index 0: DataFlair
Index 1: Swift
Index 2: Collections

Element ValueDataFlairSwiftCollections
Index012
Element ValueDataFlairSwiftCollections
Index012

The above diagram displays how every element is stored in an array associated with its index.

Add Elements to Array

We can add elements to the array. We can do this by using the built-in methods provided by Swift. The methods are as follows.

Using append()

We can add a new element at the end of the array using the append() function.

var example = ["DataFlair", "Swift"]
print(example)
example.append("Collections")
print(example)

Output:

[“DataFlair”, “Swift”]
[“DataFlair”, “Swift”, “Collections”]

We can also add the contents of one array into another. For example,

var example1 = ["DataFlair 1", "Swift 1"]
print(example1)
var example2 = ["DataFlair 2", "Swift 2"]
example1.append(contentsOf: example2)
print(example1)

Output:

[“DataFlair 1”, “Swift 1”]
[“DataFlair 1”, “Swift 1”, “DataFlair 2”, “Swift 2”]

Using insert()

We can add a new element at a given index of the array using the insert() function.

var example = ["DataFlair", "Swift"]
print(example)
example.insert("Collections", at: 1)
print(example)

Output:

[“DataFlair”, “Swift”]
[“DataFlair”, “Collections”, “Swift”]

Modify array elements

We can modify an element in the array by reassigning a new value to it.

var example = ["DataFlair", "Swift"]
print(example)
example[1] = "Collections"
print(example)

Output:

[“DataFlair”, “Swift”]
[“DataFlair”, “Collections”]

Remove elements from Array

We can remove particular or all the elements from an array.

The below table depicts the methods provided by Swift for removing elements from an array.

MethodDescription
remove()Removes the element from the given index
removeFirst()Removes the element at the start of the array
removeLast()Removes the element from the rear part of the array
removeAll()Removes all the elements in the array
var removeExample = [2, 5, 8, 23, 45, 78]
print("Original Array",removeExample)
removeExample.remove(at: 3)
print("Remove element from index 3",removeExample)
removeExample.removeFirst()
print("Remove First element",removeExample)
removeExample.removeLast()
print("Remove Last element",removeExample)
removeExample.removeAll()
print("Remove All elements",removeExample)

Output:

Original Array [2, 5, 8, 23, 45, 78]
Remove element from index 3 [2, 5, 8, 45, 78]
Remove First element [5, 8, 45, 78]
Remove Last element [5, 8, 45]
Remove All elements []

Array Methods in Swift

Swift offers several inbuilt methods for arrays. The table below depicts these methods

MethodDescription
countCounts the length of the array
isEmptyTrue if the empty array is checked; otherwise, returns false
contains()Returns true if an element is present in the array otherwise, false
reverse()Reverses the array
sort()Sorts the elements in the array
var arrayExample = ["DataFlair", "Swift", "Collections"]
print("Count:", arrayExample.count)
print("Is Empty:", arrayExample.isEmpty)
print("Contains element:", arrayExample.contains("DataFlair"))

Output:

Count: 3
Is Empty: false
Contains element: true

Loops and Arrays in Swift

We can use a for-in loop to iterate through the elements of the array. For example,

var arrayExample = ["DataFlair", "Swift", "Collections"]
for element in arrayExample{
    print(element)
}

Output:

DataFlair
Swift
Collections

Joining Arrays

We can join two arrays using the ‘+’ operator. The elements of one array are added to another array.

var arrayExample1 = ["DataFlair", "Swift", "Collections"]
var arrayExample2 = ["Arrays", "Sets"]
var arrayExample = arrayExample1 + arrayExample2
print(arrayExample)

Output:

[“DataFlair”, “Swift”, “Collections”, “Arrays”, “Sets”]

Conclusion

Arrays are the collection data types in Swift. They are used to manage multiple elements in an ordered manner. In this article, we learn how to create and access. We can add, modify and remove elements. Swift provides several inbuilt features and methods to handle elements effectively.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *