0
0
Swiftprogramming~30 mins

Why classes exist alongside structs in Swift - See It in Action

Choose your learning style9 modes available
Why Classes Exist Alongside Structs in Swift
📖 Scenario: Imagine you are building a simple app to manage information about books and their authors. You want to understand when to use structs and when to use classes in Swift.
🎯 Goal: You will create a struct and a class to represent books and authors, then see how they behave differently when copied or changed.
📋 What You'll Learn
Create a struct called Book with properties title and pages
Create a class called Author with properties name and booksWritten
Show how changing a copy of a Book struct does not affect the original
Show how changing a copy of an Author class affects the original
Print the results to observe the differences
💡 Why This Matters
🌍 Real World
Understanding when to use structs or classes helps you write safer and more efficient Swift code, especially in apps where data sharing and copying matter.
💼 Career
Swift developers often decide between structs and classes to optimize app performance and behavior, making this knowledge essential for iOS development jobs.
Progress0 / 4 steps
1
Create the Book struct
Create a struct called Book with two properties: title of type String and pages of type Int. Then create a variable firstBook of type Book with title "Swift Basics" and pages 200.
Swift
Need a hint?

Use struct keyword to define Book. Properties are declared with var.

2
Create the Author class
Create a class called Author with two properties: name of type String and booksWritten of type Int. Then create a variable firstAuthor of type Author with name "Alice" and booksWritten 3.
Swift
Need a hint?

Use class keyword and an initializer init to set properties.

3
Copy and change the Book struct
Create a new variable secondBook and set it equal to firstBook. Then change secondBook.pages to 250.
Swift
Need a hint?

Assign firstBook to secondBook and then change secondBook.pages.

4
Copy and change the Author class and print results
Create a new variable secondAuthor and set it equal to firstAuthor. Then change secondAuthor.booksWritten to 5. Finally, print firstBook.pages, secondBook.pages, firstAuthor.booksWritten, and secondAuthor.booksWritten each on its own line.
Swift
Need a hint?

Assign firstAuthor to secondAuthor, change secondAuthor.booksWritten, then print all values.