📖 Scenario: Imagine you are building a simple container that can hold items of any type, like a box that can store toys, books, or clothes. You want to make sure that when you take something out of the box, it is exactly the type you expect, so you don't get surprises or errors.
🎯 Goal: You will create a generic container in Swift that can hold any type of item. Then, you will see how generics help keep the type safe, so you only get the right type of item out of the container.
📋 What You'll Learn
Create a generic struct called Box that can hold one item of any type
Add a variable called item inside Box to store the item
Create a variable called intBox that holds an integer inside a Box
Create a variable called stringBox that holds a string inside a Box
Print the contents of both boxes showing their types
💡 Why This Matters
🌍 Real World
Generics are used in many apps to create reusable components like containers, lists, and functions that work with any data type safely.
💼 Career
Understanding generics and type safety is important for writing robust Swift code in professional iOS and macOS development.
Progress0 / 4 steps
1
Create a generic struct called Box
Write a generic struct called Box with a type parameter T. Inside it, create a variable called item of type T.
Swift
Hint
Use struct Box<T> to define a generic struct and add var item: T inside.
2
Create Box instances for Int and String
Create a variable called intBox that holds the integer 42 inside a Box. Also create a variable called stringBox that holds the string "Hello" inside a Box.
Swift
Hint
Create intBox and stringBox by calling Box(item: ...) with the correct values.
3
Access and print the items with type safety
Use print statements to display the contents of intBox.item and stringBox.item. This shows how generics keep the types safe.
Swift
Hint
Use print("intBox contains: \(intBox.item)") and similarly for stringBox.
4
Run and observe the output
Run the program and observe the printed output showing the contents of both boxes with their correct types.
Swift
Hint
The output should show the integer and string stored in the boxes, proving type safety.
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?