0
0
Swiftprogramming~10 mins

Generic type 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 that returns the input value.

Swift
func identity<[1]>(value: [1]) -> [1] {
    return value
}
Drag options to blanks, or click blank then click option'
AX
BU
CV
DT
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names in the function signature.
Forgetting to declare the generic type in angle brackets.
2fill in blank
medium

Complete the code to declare a generic struct with a property of the generic type.

Swift
struct Container<[1]> {
    var item: [1]
}
Drag options to blanks, or click blank then click option'
AElement
BItem
CT
DValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the generic type parameter and the property type.
Not using angle brackets to declare the generic type.
3fill in blank
hard

Fix the error in the generic function declaration by completing the missing generic type placeholder.

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'
AT
BU
CV
DW
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names for the parameters.
Omitting the generic type declaration.
4fill in blank
hard

Fill both blanks to declare a generic class with a method that returns the stored value.

Swift
class Box<[1]> {
    var value: [1]
    init(value: [2]) {
        self.value = value
    }
    func getValue() -> [1] {
        return value
    }
}
Drag options to blanks, or click blank then click option'
AT
BU
DV
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names in the class and initializer.
Forgetting to declare the generic type.
5fill in blank
hard

Fill all three blanks to declare a generic function that swaps two values of any type.

Swift
func swapTwoValues<[1]>(a: inout [2], b: inout [3]) {
    let temp = a
    a = b
    b = temp
}
Drag options to blanks, or click blank then click option'
AT
DU
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names for the parameters.
Omitting the generic type declaration.