0
0
Swiftprogramming~15 mins

Memberwise initializer in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Memberwise Initializer in Swift
📖 Scenario: You are creating a simple app to keep track of books in a library. Each book has a title, author, and number of pages.
🎯 Goal: Build a Swift struct called Book and use the memberwise initializer to create book instances easily.
📋 What You'll Learn
Create a struct named Book with properties title, author, and pages
Create a variable firstBook using the memberwise initializer with exact values
Create a variable secondBook using the memberwise initializer with exact values
Print the details of both books using print
💡 Why This Matters
🌍 Real World
Structs with memberwise initializers are used to model simple data objects like books, users, or products in apps.
💼 Career
Understanding memberwise initializers helps you quickly create and manage data models in Swift, a key skill for iOS development.
Progress0 / 4 steps
1
Create the Book struct
Create a struct called Book with three properties: title of type String, author of type String, and pages of type Int.
Swift
Need a hint?

Use struct Book { } and inside it declare three var properties with the exact names and types.

2
Create the first book instance
Create a variable called firstBook and initialize it using the memberwise initializer of Book with these exact values: title = "The Swift Guide", author = "John Appleseed", pages = 250.
Swift
Need a hint?

Use the syntax Book(title: "The Swift Guide", author: "John Appleseed", pages: 250) to create firstBook.

3
Create the second book instance
Create a variable called secondBook and initialize it using the memberwise initializer of Book with these exact values: title = "Learning SwiftUI", author = "Jane Developer", pages = 300.
Swift
Need a hint?

Use the memberwise initializer with the exact values to create secondBook.

4
Print the book details
Print the details of firstBook and secondBook using two separate print statements. Use string interpolation to show the title, author, and pages in this format: "Title: [title], Author: [author], Pages: [pages]".
Swift
Need a hint?

Use print("Title: \(firstBook.title), Author: \(firstBook.author), Pages: \(firstBook.pages)") and similarly for secondBook.