0
0
Swiftprogramming~10 mins

Why generics provide type safety in Swift - Test Your Understanding

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 same type it receives.

Swift
func identity<T>([1]: T) -> T {
    return value
}
Drag options to blanks, or click blank then click option'
Aelement
Bitem
Cinput
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a parameter name that is not declared, causing a compile error.
2fill in blank
medium

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

Swift
struct Box<[1]> {
    var content: T
}
Drag options to blanks, or click blank then click option'
AV
BU
CT
DX
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic parameter name that does not match the property type.
3fill in blank
hard

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

Swift
func swapValues<[1]>(_ a: inout T, _ b: inout T) {
    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 a generic parameter that does not match the function parameters.
4fill in blank
hard

Fill both blanks to create a generic function that compares two values of the same type.

Swift
func areEqual<[1]>(_ a: [2], _ b: T) -> Bool {
    return a == b
}
Drag options to blanks, or click blank then click option'
AT
BU
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type parameters for parameters that must be the same type.
5fill in blank
hard

Fill all three blanks to create a generic function that returns the first element of an array of any type.

Swift
func firstElement<[1]>(of array: [[2]]) -> [3]? {
    return array.first
}
Drag options to blanks, or click blank then click option'
AT
DU
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type parameters for the array and return type.