0
0
Swiftprogramming~20 mins

Equatable, Hashable, Comparable protocols in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Protocols Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Equatable conformance check
What is the output of this Swift code snippet?
Swift
struct Point: Equatable {
    var x: Int
    var y: Int
}

let p1 = Point(x: 3, y: 4)
let p2 = Point(x: 3, y: 4)
print(p1 == p2)
Atrue
Bfalse
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
Structs with Equatable automatically get == if all properties are Equatable.
Predict Output
intermediate
2:00remaining
Hash value consistency with Hashable
What will be printed by this Swift code?
Swift
struct User: Hashable {
    var id: Int
    var name: String
}

let user1 = User(id: 1, name: "Alice")
let user2 = User(id: 1, name: "Alice")
print(user1.hashValue == user2.hashValue)
ARuntime error
Bfalse
CCompilation error
Dtrue
Attempts:
2 left
💡 Hint
Hashable structs get synthesized hashValue based on all properties.
Predict Output
advanced
2:00remaining
Output of Comparable custom implementation
What is the output of this Swift code?
Swift
struct Box: Comparable {
    var volume: Int
    static func < (lhs: Box, rhs: Box) -> Bool {
        return lhs.volume > rhs.volume
    }
}

let b1 = Box(volume: 10)
let b2 = Box(volume: 20)
print(b1 < b2)
Atrue
Bfalse
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
The < operator is reversed in the implementation.
Predict Output
advanced
2:00remaining
Result of sorting with Comparable conformance
What will be the output of this Swift code?
Swift
struct Person: Comparable {
    var age: Int
    static func < (lhs: Person, rhs: Person) -> Bool {
        return lhs.age < rhs.age
    }
}

let people = [Person(age: 30), Person(age: 20), Person(age: 40)]
let sortedAges = people.sorted().map { $0.age }
print(sortedAges)
A[30, 20, 40]
B[40, 30, 20]
C[20, 30, 40]
DCompilation error
Attempts:
2 left
💡 Hint
Sorting uses the < operator defined in Comparable.
🧠 Conceptual
expert
3:00remaining
Why implement Equatable and Hashable together?
Why is it important to implement both Equatable and Hashable protocols consistently for a Swift type used as a dictionary key?
ABecause dictionary keys require both equality checks and hash values to store and retrieve values correctly.
BBecause <code>Hashable</code> automatically provides <code>Equatable</code> conformance, so only one is needed.
CBecause <code>Equatable</code> is only for classes and <code>Hashable</code> is only for structs.
DBecause implementing both improves performance but is not required for dictionary keys.
Attempts:
2 left
💡 Hint
Think about how dictionaries find values by keys.