0
0
Swiftprogramming~15 mins

Structs are value types (copy on assign) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Structs as Value Types in Swift
📖 Scenario: Imagine you have a simple app that keeps track of a book's details. You want to see how changing one copy of a book's information does not affect another copy.
🎯 Goal: You will create a Book struct, make a copy of it, change the copy, and then print both to see that the original stays the same. This shows how structs in Swift are value types and copy on assign.
📋 What You'll Learn
Create a struct called Book with two properties: title and author, both of type String.
Create a variable originalBook of type Book with title "Swift Basics" and author "John Appleseed".
Create a variable copiedBook and assign it the value of originalBook.
Change the title of copiedBook to "Advanced Swift".
Print the title of both originalBook and copiedBook to show they are different.
💡 Why This Matters
🌍 Real World
Structs are used in apps to represent simple data like user profiles, settings, or items. Understanding value types helps keep data safe from accidental changes.
💼 Career
Many Swift jobs require knowing when to use structs versus classes. This knowledge helps write safer and more efficient code.
Progress0 / 4 steps
1
Create the Book struct
Create a struct called Book with two String properties: title and author.
Swift
Need a hint?

Use the struct keyword and define two variables inside it.

2
Create the original Book variable
Create a variable called originalBook of type Book with title set to "Swift Basics" and author set to "John Appleseed".
Swift
Need a hint?

Create a variable and use the struct's initializer with the exact values.

3
Copy originalBook to copiedBook and change the title
Create a variable called copiedBook and assign it the value of originalBook. Then change the title of copiedBook to "Advanced Swift".
Swift
Need a hint?

Assign originalBook to copiedBook and then update the title property of copiedBook.

4
Print titles of both books
Print the title of originalBook and copiedBook on separate lines to show they are different.
Swift
Need a hint?

Use two print statements, one for each book's title.