Recall & Review
beginner
What is a generic function in Swift?
A generic function is a function that can work with any type, allowing you to write flexible and reusable code without specifying exact types.
Click to reveal answer
beginner
How do you declare a generic function in Swift?
You declare a generic function by adding a placeholder type inside angle brackets <T> before the function's parameters, like: <br>
func example<T>(param: T) { }Click to reveal answer
beginner
What does the placeholder type <T> represent in a generic function?
The placeholder <T> represents any type that will be specified when the function is called, making the function work with different types without rewriting it.
Click to reveal answer
intermediate
Why use generic functions instead of multiple functions for different types?
Generic functions reduce code duplication by handling multiple types with one function, making code easier to maintain and less error-prone.
Click to reveal answer
intermediate
Example: What does this Swift generic function do?<br><pre>func swapValues<T>(a: inout T, b: inout T) {<br> let temp = a<br> a = b<br> b = temp<br>}</pre>This function swaps the values of two variables of any type T. It uses inout parameters to change the original variables directly.
Click to reveal answer
What symbol is used to declare a generic type in a Swift function?
✗ Incorrect
Generic types are declared inside angle brackets <> in Swift.
What does the generic placeholder <T> mean in a function?
✗ Incorrect
The placeholder means the function can accept any type specified when called.
Why use generic functions?
✗ Incorrect
Generic functions allow one function to work with many types, reducing code duplication.
Which keyword is NOT part of declaring a generic function in Swift?
✗ Incorrect
'var' is not required to declare a generic function; 'func' and '' are essential.
What does this generic function do?<br>func identity<T>(value: T) -> T { return value }
✗ Incorrect
The function returns the input value exactly as it is.
Explain how to declare and use a generic function in Swift.
Think about how you write a function that can accept any type.
You got /5 concepts.
Why are generic functions useful in programming? Give an example.
Consider how one function can replace many similar functions.
You got /4 concepts.