Contents
Swift Arrays
Swift Structures
An array is a collection that can store multiple values of the same data type. Arrays in Swift are powerful because they allow you to handle collections of data efficiently. For example, if we want to store the marks of multiple students, using a list of variables would not be practical. Instead, an array can hold these marks in a single structure.
Declaring an Array
In Swift, you can declare an array with specific data types. Here’s the basic syntax:
var myArray: [Int] = [10, 20, 30]
Alternatively, Swift can infer the data type:
var myArray = [10, 20, 30]
If you want to create an empty array, use the following syntax:
var myArray: [Int] = []
Initializing an Array with Default Values
Swift allows you to create an array with a default value and a specified size using:
var myArray = Array(repeating: "Swift", count: 3)
This creates an array with three "Swift"
values.
Example:
var myArray = Array(repeating: "Swift", count: 3)
print("myArray:", myArray)
Output:
myArray: ["Swift", "Swift", "Swift"]
Accessing and Modifying Array Elements
To access array elements, use the index:
var myArray: [Int] = [10, 20, 19, 29, 45]
print("Element at index 0:", myArray[0]) // Output: 10
print("Element at index 3:", myArray[3]) // Output: 29
To modify array elements, you can use the same indexing:
var myArray: [String] = ["Swift", "Xcode", "iOS"]
myArray[0] = "SwiftUI"
myArray[1] = "Playgrounds"
print("myArray:", myArray)
Output:
myArray: ["SwiftUI", "Playgrounds", "iOS"]
Inserting and Appending Elements
To insert an element at a specific index:
var myArray: [String] = ["Swift", "Xcode"]
myArray.insert("iOS", at: 1)
print("myArray:", myArray)
Output:
myArray: ["Swift", "iOS", "Xcode"]
To add elements to the end of an array:
myArray.append("iPad")
print("myArray:", myArray)
Output:
myArray: ["Swift", "iOS", "Xcode", "iPad"]
Concatenating Arrays
You can concatenate two arrays using the +
operator:
var array1: [Int] = [1, 2, 3]
var array2: [Int] = [4, 5, 6]
var combinedArray = array1 + array2
print("combinedArray:", combinedArray)
Output:
combinedArray: [1, 2, 3, 4, 5, 6]
Iterating Over an Array
To iterate over each element in an array, use a for-in
loop:
var myArray = ["Swift", "Xcode", "iOS"]
for element in myArray {
print(element)
}
Output:
Swift
Xcode
iOS
Counting Elements in an Array
You can easily count the number of elements in an array using the count
property:
var myArray: [Int] = [10, 20, 30]
print("Number of elements:", myArray.count)
Output:
Number of elements: 3
Removing Elements from an Array
To remove an element from a specific index:
var myArray: [String] = ["Swift", "Xcode", "iOS", "iPad"]
myArray.remove(at: 2)
print("myArray after removal:", myArray)
Output:
myArray after removal: ["Swift", "Xcode", "iPad"]
If we remove "Apple"
from the array:
var myArray: [String] = ["Orange", "Apple", "Banana", "Grapes"]
if let index = myArray.firstIndex(of: "Apple") {
myArray.remove(at: index)
}
print("myArray after removing 'Apple':", myArray)
Output:
myArray after removing 'Apple': ["Orange", "Banana", "Grapes"]
Arrays Properties
An array is one of the most commonly used data types due to the benefits it provides in writing efficient programs. Similar to other programming languages, in Swift, an array is a collection of similar data types that stores data in an ordered list.
- When you assign an array to a variable, it becomes mutable, meaning you can add, remove, or modify the elements in the array.
- When you assign an array to a constant, it becomes immutable, meaning you cannot change its size or modify its elements.
// Different ways to create arrays in Swift
var myArray = [Type](count: NumberOfItems, repeatedValue: Value)
var myArray: [Int] = [10, 20, 30]
var myArray: Array = Array()
Example of Array Creation:
var programmingLanguages = ["Swift", "Python", "JavaScript"]
var numbers = [Int](count: 5, repeatedValue: 1)
Commonly Used Array Properties
1. Array.count Property
The count
property is used to find the total number of elements in the array, whether they are numbers or strings.
Syntax:
Array.count
Example:
let array1 = [10, 20, 30, 40, 50]
let array2 = ["Apple", "Banana", "Cherry"]
let array3: [Int] = []
let count1 = array1.count
let count2 = array2.count
let count3 = array3.count
print("Total elements in array1: \(count1)")
print("Total elements in array2: \(count2)")
print("Total elements in array3: \(count3)")
Output:
Total elements in array1: 5
Total elements in array2: 3
Total elements in array3: 0
2. Array.first Property
The first
property retrieves the first element of the array.
Syntax:
Array.first
Example:
let array1 = [12, 24, 36, 48]
let array2 = ["Red", "Green", "Blue"]
let array3: [Int] = []
let first1 = array1.first
let first2 = array2.first
let first3 = array3.first
print("First element of array1: \(first1 ?? -1)") // Optional handling
print("First element of array2: \(first2 ?? "None")")
print("First element of array3: \(first3 ?? -1)")
Output:
First element of array1: Optional(12)
First element of array2: Optional("Red")
First element of array3: nil
3. Array.last Property
The last
property retrieves the last element of the array.
Syntax:
Array.last
Example:
let array1 = [1, 3, 5, 7]
let array2 = ["Monday", "Tuesday", "Wednesday"]
let array3: [String] = []
let last1 = array1.last
let last2 = array2.last
let last3 = array3.last
print("Last element of array1: \(last1 ?? -1)")
print("Last element of array2: \(last2 ?? "None")")
print("Last element of array3: \(last3 ?? "Empty")")
Output:
Last element of array1: Optional(7)
Last element of array2: Optional("Wednesday")
Last element of array3: nil
4. Array.isEmpty Property
The isEmpty
property checks if the array is empty. It returns true
if the array is empty and false
otherwise.
Syntax:
Array.isEmpty
Example:
let array1 = [5, 10, 15, 20]
let array2 = [String]()
let array3 = ["Apple", "Orange"]
let empty1 = array1.isEmpty
let empty2 = array2.isEmpty
let empty3 = array3.isEmpty
print("Is array1 empty? \(empty1)")
print("Is array2 empty? \(empty2)")
print("Is array3 empty? \(empty3)")
Output:
Is array1 empty? false
Is array2 empty? true
Is array3 empty? false
How to Store Values in Arrays?
An array is a collection of elements having the same data type. Normally, to store values of a specific data type, we use variables. For example, to store marks for 5 students, we can create 5 variables. However, for a class with 50 or more students, creating separate variables for each student is inefficient and makes the code less readable. To store a large number of elements of the same type, we use arrays. Array elements can be accessed using index numbers, starting from 0 in Swift.
Below, we explore various methods to store values in an array using Swift programming.
1. Initializing an Array: You can initialize an array with elements directly at the time of declaration.
Syntax:
var myArray: [DataType] = [value1, value2, value3, ...]
Example:
// Swift program to store values in arrays
// Initializing an array of integer type
var numbers: [Int] = [1, 3, 5, 7]
// Initializing another array of character type
var characters: [Character] = ["A", "B", "C", "D"]
// Print arrays
print("Numbers Array: \(numbers)")
print("Characters Array: \(characters)")
Output:
Numbers Array: [1, 3, 5, 7]
Characters Array: ["A", "B", "C", "D"]
Example 2:
// Swift program to store values in arrays
// Initializing an array of float type
var decimals: [Float] = [1.2, 5.32, 5.56, 7.15]
// Initializing another array of string type
var words: [String] = ["Hello", "World"]
// Print arrays
print("Decimals Array: \(decimals)")
print("Words Array: \(words)")
Output:
Decimals Array: [1.2, 5.32, 5.56, 7.15]
Words Array: ["Hello", "World"]
2. Using append()
Method: The append()
method allows you to add an element to the end of the array.
Syntax:
myArray.append(value)
Example:
// Swift program to add values to arrays using append()
// Initializing an array of integer type
var numbers: [Int] = [1, 3]
// Adding elements using append()
numbers.append(5)
numbers.append(7)
// Initializing another array of character type
var characters: [Character] = ["X", "Y"]
// Adding elements using append()
characters.append("Z")
characters.append("W")
// Print arrays
print("Numbers Array: \(numbers)")
print("Characters Array: \(characters)")
Output:
Numbers Array: [1, 3, 5, 7]
Characters Array: ["X", "Y", "Z", "W"]
3. Using insert()
Method: The insert()
method adds an element to a specified index in the array.
Syntax:
myArray.insert(value, at: index)
Example:
// Swift program to insert values into arrays
// Initializing an array of integers
var numbers: [Int] = [1, 3]
// Inserting elements at specific indices
numbers.insert(5, at: 1)
numbers.insert(7, at: 2)
// Initializing another array of characters
var characters: [Character] = ["M", "N"]
// Inserting elements at specific indices
characters.insert("O", at: 1)
characters.insert("P", at: 2)
// Print arrays
print("Numbers Array: \(numbers)")
print("Characters Array: \(characters)")
Output:
Numbers Array: [1, 5, 7, 3]
Characters Array: ["M", "O", "P", "N"]
How to Remove the First element from an Array in Swift?
In Swift, an array is an ordered collection that stores values of the same type. For example, an array declared to hold integers cannot store floating-point numbers. Arrays in Swift can store duplicate values.
When an array is assigned to a variable, it is mutable, meaning you can modify its contents and size. However, when an array is assigned to a constant, it becomes immutable, and you cannot modify it.
Removing Elements in Swift Arrays
You can remove the first element from a Swift array using the removeFirst()
function. Additionally, you can use this function to remove multiple elements from the start of the array by specifying the number of elements to remove as an argument.
Syntax
arrayName.removeFirst(x: Int)
Example 1: Removing a Single Element
import Swift
// String array of authors' names
var authors = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
print("Authors before removing the first element: \(authors)")
// Remove the first element
authors.removeFirst()
print("Authors after removing the first element: \(authors)")
// Integer array of article IDs
var articleIDs = [101, 202, 303, 404, 505]
print("\nArticle IDs before removing the first element: \(articleIDs)")
// Remove the first element
articleIDs.removeFirst()
print("Article IDs after removing the first element: \(articleIDs)")
Example:
Authors before removing the first element: ["Alice", "Bob", "Charlie", "Diana", "Eve"]
Authors after removing the first element: ["Bob", "Charlie", "Diana", "Eve"]
Article IDs before removing the first element: [101, 202, 303, 404, 505]
Article IDs after removing the first element: [202, 303, 404, 505]
How to count the elements of an Array in Swift?
Swift Arrays: Counting Elements
In Swift, an array is an ordered, generic collection that stores values of the same type, such as integers, strings, or floats. You cannot mix data types in a single array. Arrays can also store duplicate values.
Arrays can be either mutable or immutable:
- Mutable arrays: Assigned to variables, allowing modifications.
- Immutable arrays: Assigned to constants, preventing modifications.
arrayName.count
Example:
import Swift
// String array of authors' names
var authors = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank"]
// Counting the total number of authors
var result1 = authors.count
// Displaying the result
print("Total number of authors:", result1)
// Empty integer array for employee IDs
var employeeIDs = [Int]()
// Counting the total number of employees
var result2 = employeeIDs.count
// Displaying the result
print("Total number of employees:", result2)
Output:
Total number of authors: 6
Total number of employees: 0
How to Reverse an Array in Swift?
Swift Arrays: Reversing Elements
In Swift, an array is a generic, ordered collection used to store values of the same type, such as integers, floats, or strings. You cannot mix types within an array. Arrays can also store duplicate values.
Arrays can be:
- Mutable: When assigned to a variable, allowing you to modify their contents and size.
- Immutable: When assigned to a constant, preventing any modifications.
Syntax:
arrayName.reverse()
Example:
import Swift
// Float array of numbers
var numbers = [10.5, 3.14, 7.89, 42.0, 1.99, 99.9]
print("Array before reversing:", numbers)
// Reversing the array using reverse() function
numbers.reverse()
print("Array after reversing:", numbers)
Output:
Array before reversing: [10.5, 3.14, 7.89, 42.0, 1.99, 99.9]
Array after reversing: [99.9, 1.99, 42.0, 7.89, 3.14, 10.5]
Swift Array joined() function
In Swift, arrays are ordered collections of values of the same type, such as integers, strings, or floats. You cannot store values of different types in the same array (e.g., a string array can only contain strings). Arrays can store duplicate values and are either mutable (if assigned to a variable) or immutable (if assigned to a constant).
The joined()
function in Swift allows you to concatenate all the elements of a string array into a single string. You can use an optional separator to specify how the elements are joined.
Syntax:
import Swift
// String array of words
var words = ["Hello", "and", "welcome", "to", "the", "Swift", "Tutorial"]
// Joining all elements with a space separator
var result1 = words.joined(separator: " ")
print("New String 1:", result1)
print("----------------------")
// Joining all elements with a hyphen separator
var result2 = words.joined(separator: "-")
print("New String 2:", result2)
Output:
New String 1: Hello and welcome to the Swift Tutorial
----------------------
New String 2: Hello-and-welcome-to-the-Swift-Tutorial
Sorting an Array in Swift+
In Swift, arrays are one of the most commonly used collections. An array is an ordered collection of elements of the same type, such as integers, strings, or floats. Swift ensures type safety by not allowing arrays to store elements of different types (e.g., an array of integers cannot hold a string value).
Arrays in Swift are generic, meaning they can store duplicate values of the same type.
- If an array is assigned to a variable, it is mutable—you can modify its contents and size.
- If an array is assigned to a constant, it is immutable—you cannot modify its contents or size.
- Swift provides a way to sort arrays in both ascending and descending order using the
sort()
method. This method allows customization of sorting using the<
(less than) and>
(greater than) operators.
Syntax:
arrayName.sort(by: operator)
Parameters:
- arrayName: The name of the array.
- operator: An optional parameter (< for ascending or > for descending).
Return Value: The sort()
method does not return a new array; instead, it modifies the original array.
Sorting an Array
Example 1: Default Sorting (Ascending Order)
import Swift
var AuthorName = ["Rohit", "Poonam", "Anu", "Susmita", "Buvan", "Mohit"]
print("Author's name before sorting:", AuthorName)
// Sorting in ascending order
AuthorName.sort()
print("Author's name after sorting:", AuthorName)
var ArticleNumber = [23, 1, 90, 3, 56, 23, 0, 6, 12]
print("----------------------")
print("Article numbers before sorting:", ArticleNumber)
// Sorting in ascending order
ArticleNumber.sort()
print("Article numbers after sorting:", ArticleNumber)
Output:
Author's name before sorting: ["Rohit", "Poonam", "Anu", "Susmita", "Buvan", "Mohit"]
Author's name after sorting: ["Anu", "Buvan", "Mohit", "Poonam", "Rohit", "Susmita"]
----------------------
Article numbers before sorting: [23, 1, 90, 3, 56, 23, 0, 6, 12]
Article numbers after sorting: [0, 1, 3, 6, 12, 23, 23, 56, 90]
Sorting in Ascending Order (Explicitly Specifying <
Operator)
import Swift
var AuthorName = ["Sumit", "Neha", "Anu", "Susmita", "Buvan", "Govind"]
print("Author's name before sorting:", AuthorName)
// Sorting explicitly in ascending order
AuthorName.sort(by: <)
print("Author's name after sorting:", AuthorName)
var ArticleNumber = [3, 20, 10, 3, 86, 23, 0, 699, 12]
print("----------------------")
print("Article numbers before sorting:", ArticleNumber)
// Sorting explicitly in ascending order
ArticleNumber.sort(by: <)
print("Article numbers after sorting:", ArticleNumber)
Output:
Author's name before sorting: ["Punit", "Neha", "Amu", "Susmita", "Fiza", "Govind"]
Author's name after sorting: ["Susmita", "Punit", "Neha", "Govind", "Fiza", "Amu"]
----------------------
Article numbers before sorting: [3, 20, 10, 3, 86, 23, 0, 699, 12]
Article numbers after sorting: [699, 86, 23, 20, 12, 10, 3, 3, 0]
Sorting in Descending Order
Example:
import Swift
var AuthorName = ["Punit", "Neha", "Amu", "Susmita", "Fiza", "Govind"]
print("Author's name before sorting:", AuthorName)
// Sorting in descending order
AuthorName.sort(by: >)
print("Author's name after sorting:", AuthorName)
var ArticleNumber = [3, 20, 10, 3, 86, 23, 0, 699, 12]
print("----------------------")
print("Article numbers before sorting:", ArticleNumber)
// Sorting in descending order
ArticleNumber.sort(by: >)
print("Article numbers after sorting:", ArticleNumber)
Output:
Author's name before sorting: ["Punit", "Neha", "Amu", "Susmita", "Fiza", "Govind"]
Author's name after sorting: ["Susmita", "Punit", "Neha", "Govind", "Fiza", "Amu"]
----------------------
Article numbers before sorting: [3, 20, 10, 3, 86, 23, 0, 699, 12]
Article numbers after sorting: [699, 86, 23, 20, 12, 10, 3, 3, 0]
How to Swap Array items in Swift?
Swift provides various generic collections, including sets, dictionaries, and arrays. An array is an ordered collection used to store values of the same type, such as strings, integers, or floats. Swift enforces type safety, so you cannot store values of a different type in an array. For example, if an array is of type Int
, adding a Float
value to it will result in an error. Arrays also allow duplicate values of the same type.
In Swift, arrays can be mutable or immutable:
- Mutable: You can modify their contents.
- Immutable: You cannot modify their contents.
Syntax:
arrayName.swapAt(index1, index2)
Parameters:
- arrayName: The name of the array.
- index1: The index of the first element to swap.
- index2: The index of the second element to swap.
Return Value:
The swapAt()
method does not return a value. It directly modifies the array by swapping the specified elements.
Example:
import Swift
// Creating an array of numbers
// The array is of type Float
var newNumber = [23.034, 1.90, 9.1, 32.34, 560.44, 21.23]
print("Array before swapping:", newNumber)
// Swapping elements at positions 1 and 2 using swapAt() method
newNumber.swapAt(1, 2)
// Displaying the result
print("Array after swapping:", newNumber)
Output:
Array before swapping: [23.034, 1.9, 9.1, 32.34, 560.44, 21.23]
Array after swapping: [23.034, 9.1, 1.9, 32.34, 560.44, 21.23]