Swift Arrays Tutorial 🎯

beginner
19 min

Swift Arrays Tutorial 🎯

Welcome to our Swift Arrays tutorial! In this comprehensive guide, we'll dive deep into one of Swift's fundamental data structures - Arrays. We'll cover everything from the basics to advanced usage, making it suitable for both beginners and intermediates. Let's get started!

What is an Array? 📝

An Array is a collection of items stored in contiguous memory locations, allowing us to access them using a single variable name and an index. Arrays are versatile and widely used in programming, making them an essential tool in your Swift toolbox.

Creating an Array in Swift 💡

Creating an Array in Swift is straightforward. Here's how to create a simple Array:

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

In this example, we've created an Array called fruits and filled it with three strings. The square brackets [] indicate that we're dealing with an Array, and the items are separated by commas.

Accessing Array Elements 💡

To access an Array element, you can use the index number inside square brackets:

swift
print(fruits[0]) // Output: Apple

In this example, fruits[0] returns the first element in the Array, which is "Apple".

Adding Elements to an Array 💡

You can add elements to an Array using the append(_:) method:

swift
fruits.append("Mango")

After adding "Mango", our fruits Array now looks like this:

swift
["Apple", "Banana", "Orange", "Mango"]

Swift Array Types 📝

Swift supports two types of Arrays:

  1. Immutable Arrays: Arrays that cannot be modified once they're created. These are denoted by the let keyword.
  2. Mutable Arrays: Arrays that can be modified after they're created. These are denoted by the var keyword.

Quiz 💡

Quick Quiz
Question 1 of 1

What is an Array in Swift?


Stay tuned for more Swift tutorials on CodeYourCraft! In the next lesson, we'll explore how to manipulate and sort Arrays in Swift. 🚀

Remember, learning takes practice, so try writing your own Swift code using the concepts we've covered. Don't forget to come back for more in-depth lessons here at CodeYourCraft! 🤝