0
0
Swiftprogramming~15 mins

Initializers and designated init in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Initializers and Designated Init in Swift
📖 Scenario: You are creating a simple app to manage information about books in a library. Each book has a title and a number of pages.
🎯 Goal: Build a Swift struct called Book with a designated initializer that sets the title and pages. Then create an instance and print its details.
📋 What You'll Learn
Create a struct called Book with two properties: title (String) and pages (Int).
Add a designated initializer init(title: String, pages: Int) to set these properties.
Create a variable myBook using the initializer with title "Swift Programming" and pages 350.
Print the book's title and pages in the format: "Title: Swift Programming, Pages: 350".
💡 Why This Matters
🌍 Real World
Initializers help set up objects with the right starting values, just like filling out a form before using a new tool.
💼 Career
Understanding initializers is essential for building apps that manage data cleanly and safely, a key skill for Swift developers.
Progress0 / 4 steps
1
Create the Book struct with properties
Create a struct called Book with two properties: title of type String and pages of type Int.
Swift
Need a hint?

Use struct keyword and declare two variables inside.

2
Add a designated initializer
Add a designated initializer init(title: String, pages: Int) inside the Book struct that sets the title and pages properties.
Swift
Need a hint?

Use init with parameters and assign them to self properties.

3
Create an instance of Book
Create a variable called myBook and initialize it using Book(title: "Swift Programming", pages: 350).
Swift
Need a hint?

Use the initializer to create myBook with the exact title and pages.

4
Print the book details
Print the details of myBook in the format: "Title: Swift Programming, Pages: 350" using print and string interpolation.
Swift
Need a hint?

Use print("Title: \(myBook.title), Pages: \(myBook.pages)") to show the output.