0
0
Swiftprogramming~15 mins

Classes are reference types in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Classes are reference types
📖 Scenario: Imagine you have a simple app that keeps track of a book's details. You want to understand how changing one book's information can affect other references to the same book.
🎯 Goal: You will create a Book class, make two variables point to the same book, change the title through one variable, and see how it affects the other variable. This will show that classes are reference types.
📋 What You'll Learn
Create a class called Book with a title property of type String
Create a variable firstBook that is an instance of Book with the title "Swift Programming"
Create a variable secondBook and assign it to firstBook
Change the title of secondBook to "Advanced Swift"
Print the title of firstBook to show it has changed
💡 Why This Matters
🌍 Real World
Understanding reference types is important when working with objects in apps, so you know how data changes affect your program.
💼 Career
Many programming jobs require knowledge of how classes and objects work, especially in Swift for iOS app development.
Progress0 / 4 steps
1
Create the Book class
Create a class called Book with a title property of type String. Initialize title using an initializer.
Swift
Need a hint?

Use class Book {} and add a var title: String inside. Add an init method to set the title.

2
Create firstBook instance
Create a variable called firstBook and assign it an instance of Book with the title "Swift Programming".
Swift
Need a hint?

Use var firstBook = Book(title: "Swift Programming") to create the instance.

3
Assign secondBook to firstBook and change title
Create a variable called secondBook and assign it to firstBook. Then change the title of secondBook to "Advanced Swift".
Swift
Need a hint?

Assign secondBook = firstBook and then set secondBook.title = "Advanced Swift".

4
Print the title of firstBook
Print the title of firstBook using print to show it has changed to "Advanced Swift".
Swift
Need a hint?

Use print(firstBook.title) to see the changed title.