Recall & Review
beginner
What does the
Equatable protocol do in Swift?The
Equatable protocol allows you to check if two values are equal using the == operator. It helps compare if two instances are the same.Click to reveal answer
beginner
Why is the
Hashable protocol important?The
Hashable protocol lets a type be used in collections like Set or as keys in Dictionary. It provides a way to create a hash value for each instance.Click to reveal answer
beginner
What does the
Comparable protocol allow you to do?The
Comparable protocol lets you compare values to see which is smaller, equal, or larger using operators like <, <=, >, and >=. It helps sort values.Click to reveal answer
intermediate
How do you make a custom Swift struct conform to
Equatable?You add
Equatable to the struct declaration. Swift can automatically create the == function if all properties are Equatable. Example: <br>struct Point: Equatable { var x: Int; var y: Int }Click to reveal answer
intermediate
What must you implement when conforming to
Hashable?You must provide a
hash(into:) method that feeds the essential properties into the hasher. This creates a hash value for the instance.Click to reveal answer
Which operator is required by the
Equatable protocol?✗ Incorrect
The
Equatable protocol requires the == operator to check equality.What does conforming to
Hashable enable for a type?✗ Incorrect
Conforming to
Hashable allows a type to be stored in sets and used as dictionary keys.Which protocol lets you compare if one value is less than another?
✗ Incorrect
Comparable provides operators like < to compare values.If a struct has only Equatable properties, what happens when you add
Equatable conformance?✗ Incorrect
Swift can automatically create the
== function if all properties are Equatable.What method must you implement for
Hashable conformance?✗ Incorrect
You must implement
hash(into:) to provide a hash value.Explain the purpose of the Equatable, Hashable, and Comparable protocols in Swift and how they differ.
Think about equality, uniqueness, and order.
You got /4 concepts.
Describe how you would make a custom struct conform to Equatable and Hashable in Swift.
Focus on protocol conformance and required methods.
You got /4 concepts.