0
0
Swiftprogramming~30 mins

Extension syntax in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Extension Syntax in Swift
📖 Scenario: Imagine you have a simple app that manages books. You want to add a new feature to calculate the age of a book since its publication without changing the original Book class.
🎯 Goal: Learn how to use extension syntax in Swift to add a new computed property to an existing class.
📋 What You'll Learn
Create a Book class with title and yearPublished properties
Add an extension to Book that adds a computed property age
Calculate the book's age based on the current year
Print the book's title and its age
💡 Why This Matters
🌍 Real World
Extensions let you add new features to existing code without changing it. This is useful when working with libraries or system classes.
💼 Career
Understanding extensions is important for Swift developers to write clean, modular, and maintainable code.
Progress0 / 4 steps
1
Create the Book class
Create a class called Book with two properties: title of type String and yearPublished of type Int. Initialize these properties with an initializer.
Swift
Need a hint?

Remember to define properties and an initializer inside the class.

2
Add an extension with a computed property
Add an extension to the Book class that adds a computed property called age of type Int. This property should calculate the difference between the current year (2024) and yearPublished.
Swift
Need a hint?

Use extension Book { var age: Int { ... } } to add the computed property.

3
Create a Book instance and access age
Create a constant called myBook that is an instance of Book with the title "Swift Programming" and yearPublished 2015. Then, create a constant called bookAge that gets the age property from myBook.
Swift
Need a hint?

Create the instance with Book(title: "Swift Programming", yearPublished: 2015) and access age.

4
Print the book's title and age
Write a print statement that outputs: "Swift Programming is 9 years old." using the title and bookAge variables with string interpolation.
Swift
Need a hint?

Use print("\(myBook.title) is \(bookAge) years old.") to show the message.