0
0
Swiftprogramming~5 mins

Equatable, Hashable, Comparable protocols in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A==
B+
C<
D!=
What does conforming to Hashable enable for a type?
AUse in sets and dictionary keys
BAutomatic sorting
CPrinting to console
DInheritance from other classes
Which protocol lets you compare if one value is less than another?
AEquatable
BHashable
CCodable
DComparable
If a struct has only Equatable properties, what happens when you add Equatable conformance?
AYou must write the <code>==</code> function manually
BSwift automatically generates the <code>==</code> function
CThe struct cannot conform to Equatable
DYou must implement <code>hash(into:)</code>
What method must you implement for Hashable conformance?
Afunc equals()
Bfunc compare(to other: Self)
Cfunc hash(into hasher: inout Hasher)
Dfunc encode()
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.