0
0
Swiftprogramming~15 mins

Struct declaration syntax in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Struct declaration syntax
📖 Scenario: Imagine you are creating a simple app to keep track of books in a library. Each book has a title and an author.
🎯 Goal: You will create a struct in Swift to represent a book with its title and author, then create an instance and print its details.
📋 What You'll Learn
Declare a struct named Book with two properties: title and author, both of type String.
Create a variable called myBook that is an instance of Book with the title "1984" and author "George Orwell".
Print the book's title and author in the format: "Title: 1984, Author: George Orwell".
💡 Why This Matters
🌍 Real World
Structs are used to group related data together, like information about a book, a user, or a product in apps.
💼 Career
Understanding struct declaration is essential for Swift developers building iOS or macOS apps to organize data cleanly and safely.
Progress0 / 4 steps
1
Create the Book struct
Declare a struct called Book with two properties: title and author, both of type String.
Swift
Need a hint?

Use struct Book {} and inside add var title: String and var author: String.

2
Create an instance of Book
Create a variable called myBook that is an instance of Book with the title "1984" and author "George Orwell".
Swift
Need a hint?

Use var myBook = Book(title: "1984", author: "George Orwell") to create the instance.

3
Print the book details
Write a print statement to display the book's title and author in the format: "Title: 1984, Author: George Orwell" using myBook.
Swift
Need a hint?

Use string interpolation with print("Title: \(myBook.title), Author: \(myBook.author)").

4
Run the program to see the output
Run the program and check that it prints exactly: Title: 1984, Author: George Orwell.
Swift
Need a hint?

Make sure your print statement matches the exact output.