Introduction
If a one-liner has to define an Array it is an ordered, random access collection. In an app, arrays are one of the most often utilised data types. Arrays are used to arrange data in your project. The Array type is used to retain items of a single type, the Element type of the array. An array can contain any type of element, including numbers, strings, and classes.
Array literals in Swift make it simple to generate arrays in your code: simply surround a comma-separated list of items with square brackets. Swift constructs an array with the provided values without any extra information, inferring the array's Element type automatically.
For instance:
// An array of 'Int' elements
let primeNumbers = [2, 3, 5, 7, 11, 13]
// An array of 'String' elements
let programmingLanguage = ["Python", "C++14", "Java"]
Use the Array(repeating: value, count: value) initializer to create an array that is pre-initialized with a fixed number of default values.
var digitCounts = Array(repeating: 0, count: 10)
print(digitCounts)
// Output : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Methods and Property of Arrays in Swift
The section will be covering the methods and features which the swift arrays provide to the user.
Accessing the elements by Values
Use a for-in loop to iterate through the contents of an array when you need to execute an operation on all of its items. It is like a for each loop in c++.
for language in programmingLanguage {
print("I can code in \(language).")
}
// Output: I can code in Python.
// Output: I can code in C++14.
// Output: I can code in Java.
Use the isEmpty property to rapidly determine whether an array contains any elements or the count property to get the array's size.
if primeNumbers.isEmpty {
print("I don't know any prime numbers.")
} else {
print("I know \(primeNumbers.count) prime numbers.")
}
For safe access to the value of the array's first and last items, use the first and last properties. These attributes are null if the array is empty.
if let firstElement = oddNumbers.first, let lastElement = oddNumbers.last {
print(firstElement, lastElement, separator: ", ")
}
// Output: 2, 13
print(emptyDoubles.first, emptyDoubles.last, separator: ", ")
// Output: nil, nil
A subscript can be used to access specific array elements. A non-empty array's initial entry is always at index zero. You can subscript an array with any integer between zero and the array's count, but not include it. A runtime error occurs when you use a negative integer or an index equal to or higher than the count.
For example:
print(primeNumbers[0], primeNumbers[3], separator: ", ")
// Output: 2, 7
print(emptyDoubles[0])
// Triggers runtime error: Index out of range
Adding and Removing Elements
Suppose you need to store a list of the names of students that are signed up for a class you’re teaching. During the registration period, you need to add and remove names as students add and drop the class.
var students = ["Ram", "Mohan", "Lata"]
To add single elements to the end of an array, use the append(value) method. Add multiple elements at the same time by passing another array or a sequence of any kind to the append(contentsOf: []) method. For example:
students.append("Aman")
students.append(contentsOf: ["Pratyush", "Kushi"])
// ["Ram", "Mohan", "Lata", "Aman", "Pratyush", "Kushi"]
You can add new elements in the middle of an array by using the insert(value, at: indexvalue) method for single elements and by using insert(contentsOf:[], at: indexvalue) to insert multiple elements from another collection or array literal. The elements at that index and later indices are shifted back to make room. For example
students.insert("Sai", at: 3)
// ["Ram", "Mohan", "Lata", “Sia”, "Aman", "Pratyush", "Kushi"]
To remove elements from an array, use the remove(at:), removeSubrange(value: value), and removeLast() methods.
// Ram's family is moving to another place
students.remove(at: 0)
// ["Mohan", "Lata", “Sia”, "Aman", "Pratyush", "Kushi"]
// Kushi is also left to another place
students.removeLast()
// ["Mohan", "Lata", “Sia”, "Aman", "Pratyush"]
You can update an existing element with a new value by assigning the new value to the subscript.
if let i = students.firstIndex(of: "Sia") {
students[i] = "Sita"
}
// ["Mohan", "Lata", “Sita”, "Aman", "Pratyush"]
Growing the size of an Array
Each array sets aside a certain amount of memory for its contents. When you add items to an array and the array's reserved capacity is reached, the array allocates more memory and transfers its elements to the additional storage. The new storage is much larger than the old storage. Appending one element in constant time, averaging the performance of numerous append operations, is the result of this exponential growth method. Append operations that cause reallocation incurs a performance cost, but as the array becomes larger, they become less common.
To prevent intermediary reallocations, utilise the reserveCapacity(value) function before adding to the array if you know roughly how many elements you'll need to hold. Determine how many additional elements the array can store without allocating more storage by using the capacity and count attributes.
This storage is a contiguous block of memory for arrays of most Element kinds. This storage can be a contiguous block of memory or an instance of NSArray for arrays with an Element type of class or @objc protocol type. There are no assurances concerning representation or performance in this scenario since any arbitrary subclass of NSArray can become an Array.
Array With Mixed Data Types
Arrays that contain items of a single data type have been used till now. In Swift, however, we may build arrays that include components of several data types.For example,
// array with String and integer data
var address: [Any] = ["Chembur", 57730]
print(address)