0
0
Swiftprogramming~10 mins

Type constraints with protocol conformance 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 declare a generic function that accepts any type conforming to the Comparable protocol.

Swift
func findMax<T: [1]>(_ a: T, _ b: T) -> T {
    return a > b ? a : b
}
Drag options to blanks, or click blank then click option'
ACodable
BComparable
CEquatable
DHashable
Attempts:
3 left
💡 Hint
Common Mistakes
Using Equatable instead of Comparable, which only supports equality checks.
Using Codable or Hashable which do not provide comparison operators.
2fill in blank
medium

Complete the code to constrain the generic type to the Hashable protocol.

Swift
func checkAndHash<T: [1]>(_ value: T) -> Int {
    return value.hashValue
}
Drag options to blanks, or click blank then click option'
AHashable
BCodable
CComparable
DEquatable
Attempts:
3 left
💡 Hint
Common Mistakes
Using Equatable instead of Hashable, as Equatable lacks hashValue.
Using Codable or Comparable which do not provide hashValue.
3fill in blank
hard

Fix the error in the generic function declaration by filling the correct protocol conformance.

Swift
func compareItems<T: [1]>(_ first: T, _ second: T) -> Bool {
    return first == second
}
Drag options to blanks, or click blank then click option'
ACodable
BComparable
CEquatable
DHashable
Attempts:
3 left
💡 Hint
Common Mistakes
Using Comparable which supports ordering but not just equality.
Using Codable or Hashable which do not define == operator.
4fill in blank
hard

Fill both blanks to declare a generic function where T conforms to Codable and U conforms to Hashable.

Swift
func processItems<T: [1], U: [2]>(item1: T, item2: U) {
    print(item1)
    print(item2.hashValue)
}
Drag options to blanks, or click blank then click option'
ACodable
BEquatable
CHashable
DComparable
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the protocols for T and U.
Using Comparable or Equatable incorrectly.
5fill in blank
hard

Fill all three blanks to create a generic function where T conforms to Comparable, U conforms to Equatable, and V conforms to Codable.

Swift
func genericFunction<T: [1], U: [2], V: [3]>(a: T, b: U, c: V) {
    if a > a {
        print(b == b)
    }
    print(c)
}
Drag options to blanks, or click blank then click option'
AComparable
BEquatable
CCodable
DHashable
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing which protocol supports which operator.
Using Hashable instead of Codable for printing.