Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a generic function named swapValues.
Swift
func swapValues<[1]>(_ a: inout [1], _ b: inout [1]) { let temp = a a = b b = temp }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type like Int instead of a generic placeholder.
Forgetting to declare the generic type in angle brackets.
✗ Incorrect
The generic type placeholder is usually a single uppercase letter like 'T'.
2fill in blank
mediumComplete the code to call the generic function swapValues with two integer variables.
Swift
var x = 5 var y = 10 swapValues(&[1], &y)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a variable that is not declared.
Passing the same variable twice.
✗ Incorrect
You need to pass the variable 'x' to swap with 'y'.
3fill in blank
hardFix the error in the generic function declaration by completing the blank.
Swift
func printValue<[1]>(value: [1]) { print(value) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type instead of a generic placeholder.
Using a lowercase letter as a generic placeholder.
✗ Incorrect
The generic type placeholder should be a single uppercase letter like 'T'.
4fill in blank
hardFill both blanks to declare a generic function identity that returns the same value it receives.
Swift
func identity<[1]>(_ value: [2]) -> [1] { return value }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for the parameter and return type.
Using concrete types instead of the generic placeholder.
✗ Incorrect
The generic placeholder 'T' is used both to declare the generic type and as the parameter type.
5fill in blank
hardFill all three blanks to declare a generic function compare that returns true if two values are equal.
Swift
func compare<[1]>(_ a: [2], _ b: [3]) -> Bool where [1]: Equatable { return a == b }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different placeholders for parameters and constraint.
Omitting the Equatable constraint.
✗ Incorrect
The generic placeholder 'T' is used consistently for the type parameters and constrained to Equatable.