Swift Arrays and Operations on Arrays
Arrays are an important data structure in programming, and Swift provides a lot of functionality for working with arrays. An array is a collection of elements of the same type, stored in contiguous memory locations. In Swift, arrays are used to store ordered lists of values.
Creating an Array
In Swift, arrays can be created in a number of ways. One way to create an array is to use an array literal, which is a comma-separated list of values inside square brackets.
1var numbers = [1, 2, 3, 4, 5]
Another way to create an array is to use the Array
initializer:
1var names = Array<String>()
This creates an empty array of strings.
Accessing Array Elements
You can access the elements of an array using the index of the element. The index of the first element in an array is 0.
1var fruits = ["apple", "banana", "cherry"] 2print(fruits[0]) // "apple"
You can also use the count
property of an array to get the number of elements in the array.
1print(fruits.count) // 3
Modifying Array Elements
You can modify the elements of an array by assigning a new value to an element using its index.
1fruits[0] = "orange" 2print(fruits) // ["orange", "banana", "cherry"]
You can also use the append
method to add an element to the end of the array.
1fruits.append("grape") 2print(fruits) // ["orange", "banana", "cherry", "grape"]
The insert
method can be used to insert an element at a specific index.
1fruits.insert("kiwi", at: 1) 2print(fruits) // ["orange", "kiwi", "banana", "cherry", "grape"]
The remove
method can be used to remove an element from the array.
1fruits.remove(at: 2) 2print(fruits) // ["orange", "kiwi", "cherry", "grape"]
Iterating Over an Array
You can use a for-in
loop to iterate over an array.
1for fruit in fruits { 2 print(fruit) 3}
This will print out each element of the array.
1orange 2kiwi 3cherry 4grape