Book with properties title (String) and pages (Int).Book conform to Equatable and Hashable protocols automatically.Book conform to Comparable by comparing books based on their pages count.Comparable conformance.Book with properties title (String) and pages (Int).Book conform to Equatable and Hashable protocols automatically.Book conform to Comparable by comparing books based on their pages count.Comparable conformance.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).Use struct Book {} and add two let properties inside. Then create an array books with the exact Book instances.
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.Add : Equatable, Hashable after Book in the struct definition.
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.Add , Comparable after Hashable and write the < function comparing pages.
sortedBooks by sorting the books array. Then use a for loop to print each book's title from sortedBooks.Use books.sorted() to sort and then print each title in a for loop.
Which protocol in Swift allows you to check if two instances of a type are equal using ==?
==.Which of the following is the correct way to declare a struct Person that conforms to Equatable and Hashable?
struct Person: ??? {
var name: String
var age: Int
}What will be the output of the following Swift code?
struct Item: Comparable {
var value: Int
static func < (lhs: Item, rhs: Item) -> Bool {
return lhs.value < rhs.value
}
}
let items = [Item(value: 3), Item(value: 1), Item(value: 2)]
let sortedValues = items.sorted().map { $0.value }
print(sortedValues)< operator compares value properties to sort ascending.Identify the error in this Swift struct that tries to conform to Hashable:
struct Book: Hashable {
var title: String
var pages: Int
func hash(into hasher: inout Hasher) {
hasher.combine(title)
}
}title is combined; pages is missing, causing incorrect hashing.You want to create a struct Player that can be stored in a Set, compared for equality, and sorted by score descending. Which protocols should Player conform to, and how should you implement the sorting?
< operator to compare scores descending by reversing comparison.Pass the test and this pattern moves unknown