0
0
Swiftprogramming~5 mins

Generic function declaration in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A<>
B()
C[]
D{}
What does the generic placeholder <T> mean in a function?
AAny type specified when calling the function
BA variable name
CA specific type like Int
DA constant value
Why use generic functions?
ATo avoid using functions
BTo write the same function multiple times
CTo make code slower
DTo handle different types with one function
Which keyword is NOT part of declaring a generic function in Swift?
Afunc
Bvar
C<T>
Dinout
What does this generic function do?<br>func identity<T>(value: T) -> T { return value }
ASwaps two values
BChanges the input value
CReturns the input value unchanged
DReturns a fixed value
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.