0
0
Swiftprogramming~15 mins

Reference sharing and side effects in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Swift Arrays: Copy-on-Write and No Side Effects
📖 Scenario: Imagine you have a list of favorite fruits that you share with a friend by assigning the array. See what happens when the friend adds a new fruit to the list.
🎯 Goal: You will create a list of fruits, assign it to another variable, add to one, then print both to show how mutations behave with Swift arrays.
📋 What You'll Learn
Create a variable called fruits with an array of strings: ["Apple", "Banana", "Cherry"]
Create a variable called friendFruits and assign it to fruits
Add the string "Date" to friendFruits
Print both fruits and friendFruits to show their contents
💡 Why This Matters
🌍 Real World
Understanding how data is shared or copied helps avoid bugs when multiple parts of a program use the same data.
💼 Career
Many programming jobs require managing data carefully to prevent unexpected changes and bugs, especially when working with collections.
Progress0 / 4 steps
1
Create the initial fruits array
Create a variable called fruits and set it to the array ["Apple", "Banana", "Cherry"].
Swift
Need a hint?

Use var fruits = ["Apple", "Banana", "Cherry"] to create the array.

2
Assign the fruits array to friendFruits
Create a variable called friendFruits and assign it to the existing fruits variable.
Swift
Need a hint?

Use var friendFruits = fruits to share the array.

3
Add a new fruit to friendFruits
Add the string "Date" to the friendFruits array using the append method.
Swift
Need a hint?

Use friendFruits.append("Date") to add the new fruit.

4
Print both fruits and friendFruits
Print both fruits and friendFruits using two separate print statements to show their contents.
Swift
Need a hint?

Use print(fruits) and print(friendFruits) to show the arrays.