Iterating over Arrays in Swift 🎯

beginner
21 min

Iterating over Arrays in Swift 🎯

Welcome to our comprehensive guide on iterating over arrays in Swift! Let's dive into the world of Swift and learn how to work with arrays, one of the most fundamental data structures in programming.

What is an Array? 📝

An array is a collection of items stored at contiguous memory locations. In Swift, arrays are type-safe, meaning each array must have a specific element type.

Creating an Array 💡

To create an array, you can use square brackets [] and separate elements with commas. Here's an example:

swift
var fruits = ["Apple", "Banana", "Orange"]

In the example above, we've created an array named fruits with three elements of type String.

Accessing Array Elements 💡

You can access array elements by their index. In Swift, array indices start at 0. Here's how to access the first and last elements of the fruits array:

swift
print(fruits[0]) // Prints "Apple" print(fruits[2]) // Prints "Orange"

Iterating over Arrays 💡

Now that you know how to create and access array elements, it's time to learn how to iterate over arrays. Swift provides several ways to iterate over arrays. Let's explore two common methods: for-in loop and map() function.

for-in Loop 💡

The for-in loop is a common way to iterate over arrays in Swift. Here's how to use it:

swift
for fruit in fruits { print(fruit) }

In the example above, the for-in loop iterates over each element in the fruits array and prints it to the console.

map() Function 💡

The map() function applies a given closure to each element in an array and returns a new array with the transformed elements. Here's an example:

swift
let capitalizedFruits = fruits.map { fruit -> String in return fruit.capitalized } print(capitalizedFruits) // Prints ["Apple", "Banana", "Orange"]

In the example above, the map() function is used to capitalize each fruit name and return a new array with the transformed elements.

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `for-in` loop do in Swift?

Wrapping Up ✅

In this tutorial, you learned how to create arrays, access array elements, and iterate over arrays using the for-in loop and map() function in Swift. We hope you found this tutorial helpful and engaging. Happy coding! 🚀

Stay tuned for our next tutorial on more advanced Swift array features! 🎯