0
0
Swiftprogramming~30 mins

Equatable, Hashable, Comparable protocols in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Equatable, Hashable, and Comparable Protocols in Swift
📖 Scenario: You are creating a simple app to manage a collection of books. Each book has a title and a number of pages. You want to compare books, check if two books are the same, and use books in sets or as dictionary keys.
🎯 Goal: Build a Swift program that defines a Book struct which conforms to Equatable, Hashable, and Comparable protocols. You will create books, compare them, and print sorted books.
📋 What You'll Learn
Define a struct called Book with properties title (String) and pages (Int).
Make Book conform to Equatable and Hashable protocols automatically.
Make Book conform to Comparable by comparing books based on their pages count.
Create a list of books with exact titles and pages.
Sort the list of books using the Comparable conformance.
Print the sorted list of book titles.
💡 Why This Matters
🌍 Real World
Managing collections of items like books, contacts, or products often requires comparing, checking equality, and using them in sets or dictionaries.
💼 Career
Understanding these protocols is essential for Swift developers to write efficient, clean, and correct code when working with custom data types.
Progress0 / 4 steps
1
Create the Book struct with properties
Define a struct called Book with two properties: title of type String and pages of type Int. Create a constant array called books with these exact entries: Book(title: "Swift Basics", pages: 200), Book(title: "Advanced Swift", pages: 350), Book(title: "iOS Development", pages: 300).
Swift
Need a hint?

Use struct Book {} and add two let properties inside. Then create an array books with the exact Book instances.

2
Make Book conform to Equatable and Hashable
Make the Book struct conform to the Equatable and Hashable protocols by adding them after the struct name. No need to write extra code because Swift can synthesize them automatically.
Swift
Need a hint?

Add : Equatable, Hashable after Book in the struct definition.

3
Make Book conform to Comparable by pages
Add Comparable conformance to the Book struct. Implement the required static function func < (lhs: Book, rhs: Book) -> Bool that returns true if lhs.pages is less than rhs.pages.
Swift
Need a hint?

Add , Comparable after Hashable and write the < function comparing pages.

4
Sort and print the book titles
Create a constant called sortedBooks by sorting the books array. Then use a for loop to print each book's title from sortedBooks.
Swift
Need a hint?

Use books.sorted() to sort and then print each title in a for loop.