0
0
Swiftprogramming~30 mins

Adding initializers via extension in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Adding initializers via extension
📖 Scenario: You are creating a simple app that manages information about books. You want to add a new way to create book objects easily by adding an initializer through an extension.
🎯 Goal: Learn how to add a new initializer to an existing Book struct using an extension in Swift.
📋 What You'll Learn
Create a Book struct with two properties: title and author, both of type String.
Add an extension to Book that includes a new initializer which takes a single String parameter called combined.
The new initializer should split the combined string by a dash " - " and assign the first part to title and the second part to author.
Create a Book instance using the new initializer with the string "1984 - George Orwell".
Print the title and author of the created Book.
💡 Why This Matters
🌍 Real World
Adding initializers via extensions helps you add new ways to create objects without changing the original code. This is useful when working with libraries or when you want to keep your code organized.
💼 Career
Understanding how to extend existing types and add initializers is important for Swift developers working on apps that handle data parsing, user input, or need flexible object creation.
Progress0 / 4 steps
1
Create the Book struct
Create a struct called Book with two properties: title and author, both of type String.
Swift
Need a hint?

Use struct Book { var title: String; var author: String } to define the structure.

2
Add an extension with a new initializer
Add an extension to Book that defines a new initializer init(combined: String). Inside it, split the combined string by " - " and assign the first part to title and the second part to author.
Swift
Need a hint?

Use extension Book { init(combined: String) { ... } } and split(separator: "-") to separate the string.

3
Create a Book instance using the new initializer
Create a constant book using the new initializer with the string "1984 - George Orwell".
Swift
Need a hint?

Create the book with let book = Book(combined: "1984 - George Orwell").

4
Print the book's title and author
Print the title and author of the book constant using two separate print statements.
Swift
Need a hint?

Use print(book.title) and print(book.author) to show the values.