0
0
Swiftprogramming~10 mins

Generic function declaration 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 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'
ADouble
BInt
CString
DT
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.
2fill in blank
medium

Complete 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'
Ay
Bz
Cx
Da
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a variable that is not declared.
Passing the same variable twice.
3fill in blank
hard

Fix 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'
AT
BValue
CInt
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type instead of a generic placeholder.
Using a lowercase letter as a generic placeholder.
4fill in blank
hard

Fill 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'
AT
BInt
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for the parameter and return type.
Using concrete types instead of the generic placeholder.
5fill in blank
hard

Fill 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'
AT
DU
Attempts:
3 left
💡 Hint
Common Mistakes
Using different placeholders for parameters and constraint.
Omitting the Equatable constraint.