0
0
Swiftprogramming~15 mins

Convenience initializers in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Convenience Initializers in Swift
📖 Scenario: You are creating a simple app to manage information about books. Each book has a title and an author. Sometimes, you only know the title and want to create a book with a default author.
🎯 Goal: Build a Book class with a main initializer and a convenience initializer that sets a default author when only the title is known.
📋 What You'll Learn
Create a Book class with properties title and author
Write a main initializer that takes title and author as parameters
Add a convenience initializer that takes only title and sets author to "Unknown"
Create an instance using the convenience initializer and print its details
💡 Why This Matters
🌍 Real World
Convenience initializers help create objects easily when some information is missing or default values are common, like creating user profiles or product items.
💼 Career
Understanding initializers and convenience initializers is essential for Swift developers building apps with clean and reusable code.
Progress0 / 4 steps
1
Create the Book class with properties and main initializer
Create a class called Book with two String properties: title and author. Write an initializer init(title: String, author: String) that sets these properties.
Swift
Need a hint?

Remember to use self to assign the parameters to the properties inside the initializer.

2
Add a convenience initializer with default author
Add a convenience init(title: String) initializer inside the Book class. It should call the main initializer with author set to "Unknown".
Swift
Need a hint?

Use self.init inside the convenience initializer to call the main initializer.

3
Create a Book instance using the convenience initializer
Create a constant book1 using the convenience initializer with the title "Swift Programming".
Swift
Need a hint?

Use let book1 = Book(title: "Swift Programming") to create the instance.

4
Print the book details
Print the title and author of book1 using print. Format the output as: "Title: Swift Programming, Author: Unknown".
Swift
Need a hint?

Use string interpolation with \(book1.title) and \(book1.author) inside the print statement.