What is the main benefit of using generics in Swift?
Generics allow you to write flexible and reusable code while ensuring type safety by working with any data type without losing the information about the type.
Click to reveal answer
beginner
How do generics help prevent type errors in Swift?
Generics enforce that the types used are consistent throughout the code, so you cannot accidentally mix different types, which prevents many runtime errors.
Click to reveal answer
intermediate
Explain with an example why generics provide type safety.
If you create a generic function to swap two values of the same type, Swift ensures both values are the same type at compile time, so you can't swap an Int with a String by mistake.
Click to reveal answer
beginner
What happens if you try to use different types with a generic function expecting the same type?
Swift will give a compile-time error because generics require the types to match, which protects your code from type mismatches.
Click to reveal answer
beginner
Why is type safety important in programming?
Type safety helps catch errors early during development, making programs more reliable and easier to maintain by preventing unexpected type mismatches.
Click to reveal answer
What does Swift generics ensure when used in functions or types?
AThat the types used are consistent and checked at compile time
BThat the code runs faster at runtime
CThat only integers can be used
DThat the program ignores type mismatches
✗ Incorrect
Generics enforce type consistency at compile time, preventing type errors.
Why can generics prevent runtime errors?
ABecause they check types during compilation
BBecause they convert all types to strings
CBecause they disable type checking
DBecause they only work with one type
✗ Incorrect
Generics check types at compile time, so type errors are caught before running the program.
What will happen if you try to swap an Int and a String using a generic swap function expecting the same type?
AThe swap will succeed
BCompile-time error
CRuntime error
DThe program will ignore the swap
✗ Incorrect
Swift's generics require the types to match, so swapping different types causes a compile-time error.
Which of these is NOT a benefit of generics?
AType safety
BFlexibility
CCode reuse
DIgnoring type mismatches
✗ Incorrect
Generics do not ignore type mismatches; they enforce type safety.
How do generics improve code readability?
ABy removing type annotations
BBy hiding all types
CBy making code work with any type clearly and safely
DBy forcing all variables to be strings
✗ Incorrect
Generics make it clear that code works with any type while keeping type safety.
Explain in your own words why generics provide type safety in Swift.
Think about how generics check types before the program runs.
You got /4 concepts.
Describe a simple example where generics prevent a type mismatch error.
Imagine swapping two values of different types.
You got /4 concepts.
Practice
(1/5)
1. Why do generics in Swift provide type safety?
easy
A. They convert all types to strings automatically.
B. They allow any type without restrictions, so errors are ignored.
C. They only work with integer types.
D. They ensure the types used match the expected types at compile time.
Solution
Step 1: Understand generics role in type checking
Generics let you write code that works with any type but still checks that the types match when used.
Step 2: Recognize compile-time safety
This checking happens during compilation, so errors are caught early before running the program.
Final Answer:
They ensure the types used match the expected types at compile time. -> Option D
Quick Check:
Generics = Compile-time type matching [OK]
Hint: Generics check types before running code to avoid errors [OK]
Common Mistakes:
Thinking generics allow any type without checks
Believing generics convert types automatically
Assuming generics only work with specific types
2. Which of the following is the correct syntax to declare a generic function that swaps two values in Swift?
easy
A. func swapValues<T>(a: inout T, b: inout T) {}
B. func swapValues(a: T, b: T) {}
C. func swapValues<T>(a: T, b: T) -> T {}
D. func swapValues<T>(a: T, b: T) {}
Solution
Step 1: Identify generic function syntax
Generic functions use angle brackets <T> after the function name to declare a type parameter.
Step 2: Check parameter usage for swapping
Swapping requires inout parameters to modify the original variables.
The function printItem accepts any type T and prints it using string interpolation.
Step 2: Analyze calls with different types
First call passes an integer 42, second call passes a string "Hello". Both are valid and print accordingly.
Final Answer:
Item: 42
Item: Hello -> Option A
Quick Check:
Generic function prints each item correctly [OK]
Hint: Generic functions adapt to each type passed [OK]
Common Mistakes:
Expecting type mismatch error
Assuming output repeats same value
Confusing string interpolation syntax
4. Identify the error in this generic Swift function and fix it:
func addItems<T>(a: T, b: T) -> T {
return a + b
}
medium
A. No error, function works for all types.
B. Error: '+' operator not defined for all types T; constrain T to Numeric.
C. Error: Missing return type; should be '-> Int'.
D. Error: Parameters should be optional types.
Solution
Step 1: Analyze operator usage with generics
The '+' operator only works with types that support addition, not all types T.
Step 2: Apply type constraint to fix error
Constrain T to Numeric protocol to ensure '+' is valid for T.
Final Answer:
Error: '+' operator not defined for all types T; constrain T to Numeric. -> Option B
Quick Check:
Operator '+' requires Numeric constraint [OK]
Hint: Add constraints to generic types when using operators [OK]
Common Mistakes:
Assuming '+' works for any generic type
Ignoring need for protocol constraints
Changing return type unnecessarily
5. You want to create a generic function that returns the middle element of an array. Which approach ensures type safety and works for any array type in Swift?