0
0
Swiftprogramming~5 mins

Generic type declaration in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a generic type declaration in Swift?
A generic type declaration lets you write flexible, reusable functions and types that can work with any type, instead of a specific one.
Click to reveal answer
beginner
How do you declare a generic function in Swift?
You add a placeholder type inside angle brackets after the function name, like <T>, and use T as a type inside the function.
Click to reveal answer
intermediate
Example: What does this Swift code do?
func swapValues<T>(a: inout T, b: inout T) { let temp = a; a = b; b = temp }
This function swaps the values of two variables of any type T. It uses generics so it works with Int, String, or any other type.
Click to reveal answer
intermediate
How do you declare a generic type (like a class or struct) in Swift?
You add a placeholder type inside angle brackets after the type name, for example struct Box<T> { var value: T }.
Click to reveal answer
beginner
Why use generic type declarations instead of specific types?
Generics let you write code once and use it with many types, making your code reusable, safer, and easier to maintain.
Click to reveal answer
What symbol is used to declare a generic type placeholder in Swift?
A[]
B{}
C()
D<>
Which keyword is used to declare a generic function in Swift?
Afunc
Bgeneric func
Cfunc<T>
Dfunc with <T>
What does the generic type T represent in Swift?
AA placeholder for any type
BA specific type called T
CA variable name
DA function name
Which of these is a correct generic struct declaration in Swift?
Astruct Box<T> = { var value: T }
Bstruct Box<T> { var value: T }
Cstruct Box<T> (var value: T)
Dstruct Box { var value: T }
Why are generics useful in Swift?
AThey make code run faster
BThey replace all functions
CThey allow writing reusable and type-safe code
DThey are only for classes
Explain how to declare and use a generic function in Swift.
Think about how you write <T> after the function name and use T as a type.
You got /3 concepts.
    Describe the benefits of using generic type declarations in Swift programming.
    Why would you want one function or type to work with many types?
    You got /4 concepts.