Use Arrays in Swift
Written by Team Kodeco
Arrays are a fundamental data structure that allows you to store a collection of items of the same type in a single variable. They are ordered, meaning that each item in the array has a specific index, starting at 0, that can be used to access its value.
Here’s an example of how to declare and use an array in Swift:
// Declare an array of integers
var numbers = [1, 2, 3]
// Alternative way with manual type annotation
var altNumbers: [Int] = [1, 2, 3]
// Print the first item in the array
print(numbers[0]) // Output: 1
// Add an item to the array
numbers.append(4)
// Remove an item from the array
numbers.remove(at: 2)
// Iterate over the array
for number in numbers {
print(number)
}
// Output: 1
// 2
// 4
It’s important to note that the type of the array must be specified when it’s declared, for example var numbers: [Int]
or inferred from the initializer, for example var numbers = [1, 2, 3]
.
Create an Empty Array
You can create an empty array of a specific type by either using the Array
type, or by using type annotation:
var numbers = Array<Int>() // Method 1
var altNumbers: [Int] = [] // Method 2
Get the Length of an Array
You can use the count
property to get the count of elements in an array:
var numbers = [1, 2, 3]
numbers.count // 3
Check if an Array is Empty
You can use the isEmpty
property to check if the array is empty or not:
var numbers = [1, 2, 3]
numbers.isEmpty // false