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