0
0
Swiftprogramming~10 mins

Equatable, Hashable, Comparable protocols in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to make the struct conform to Equatable.

Swift
struct Point: Equatable {
    var x: Int
    var y: Int

    static func ==(lhs: Point, rhs: Point) -> Bool {
        return lhs.x [1] rhs.x && lhs.y == rhs.y
    }
}
Drag options to blanks, or click blank then click option'
A+
B==
C!=
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' causes the comparison to be wrong.
Using '+' or '-' operators here does not make sense.
2fill in blank
medium

Complete the code to make the struct conform to Hashable by implementing hash(into:).

Swift
struct Person: Hashable {
    var name: String
    var age: Int

    func hash(into hasher: inout Hasher) {
        hasher.[1](name)
        hasher.combine(age)
    }
}
Drag options to blanks, or click blank then click option'
Aappend
Badd
Cinsert
Dcombine
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'append' or 'add' which are not methods of Hasher.
Forgetting to combine all properties.
3fill in blank
hard

Fix the error in the Comparable conformance by completing the less-than operator.

Swift
struct Rectangle: Comparable {
    var width: Int
    var height: Int

    static func < (lhs: Rectangle, rhs: Rectangle) -> Bool {
        return lhs.width [1] rhs.width
    }
}
Drag options to blanks, or click blank then click option'
A<
B>
C==
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using > or >= reverses the comparison logic.
Using == does not define ordering.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.

Swift
let words = ["apple", "cat", "banana", "dog"]
var lengths = [String: Int]()
for word in words {
    if word.[1] > 3 {
        lengths[word] = word.[2]
    }
}
Drag options to blanks, or click blank then click option'
Acount
Blength
Csize
DlengthOf
Attempts:
3 left
💡 Hint
Common Mistakes
Using properties like 'length' or 'size' which do not exist in Swift strings.
Using different properties for the two blanks causes errors.
5fill in blank
hard

Fill all three blanks to create a sorted array of unique names using Set and sorted().

Swift
let names = ["Anna", "Bob", "Anna", "Charlie"]
let uniqueSortedNames = Array([1](names)).[2]() [3] { $0 < $1 }
Drag options to blanks, or click blank then click option'
ASet
Bsorted
Csorted(by:)
DArray
Attempts:
3 left
💡 Hint
Common Mistakes
Using sorted() without by: when a closure is provided causes errors.
Not converting back to Array if needed.