Bird
Raised Fist0
Swiftprogramming~10 mins

Generic type declaration in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Generic type declaration
Start
↓
Declare generic type <T>
↓
Use <T> as placeholder
↓
Create instance with specific type
↓
Use instance with that type
↓
End
This flow shows declaring a generic type placeholder <T>, using it in code, then creating instances with specific types.
Execution Sample
Swift
struct Box<T> {
    var value: T
}

let intBox = Box<Int>(value: 10)
let strBox = Box<String>(value: "Hi")
Defines a generic struct Box that can hold any type T, then creates two instances with Int and String types.
Execution Table
StepActionGeneric Type <T>Instance CreatedValue Stored
1Declare struct Box with generic <T><T> is a placeholderNo instance yetNo value yet
2Create intBox as Box<Int><T> replaced by IntintBox10 (Int)
3Create strBox as Box<String><T> replaced by StringstrBox"Hi" (String)
4Access intBox.valueIntintBox10
5Access strBox.valueStringstrBox"Hi"
💡 All instances created and values stored; generic type replaced by specific types Int and String.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
intBoxnilBox<Int>(value: 10)Box<Int>(value: 10)Box<Int>(value: 10)
strBoxnilnilBox<String>(value: "Hi")Box<String>(value: "Hi")
Key Moments - 3 Insights
Why do we use <T> instead of a real type name when declaring Box?
Because <T> is a placeholder that lets Box work with any type. The actual type is chosen when creating an instance, as shown in steps 2 and 3.
What happens to <T> when we create intBox as Box<Int>?
At step 2, <T> is replaced by Int for that instance, so intBox.value holds an Int value.
Can intBox hold a String value?
No, because intBox is Box<Int>, it only holds Int values. strBox is Box<String> and holds String values, as seen in steps 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what type does <T> represent when creating strBox?
AString
BDouble
CInt
DGeneric placeholder still
💡 Hint
Check step 3 in the execution table where strBox is created.
At which step is the first instance of Box created?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look for when intBox is assigned a value in the execution table.
If we tried to assign a String to intBox.value, what would happen?
AIt would work fine
BCompile error because intBox expects Int
CintBox.value would change type to String
DRuntime error only
💡 Hint
Refer to variable_tracker and key moment about type safety.
Concept Snapshot
Generic type declaration syntax:
struct Box<T> { var value: T }

- <T> is a placeholder type
- Replace <T> with real type when creating instance
- Enables code reuse for any type
- Type safety ensured by compiler
- Use angle brackets <> for generics
Full Transcript
This visual execution shows how to declare and use a generic type in Swift. We start by declaring a struct Box with a generic placeholder <T>. This placeholder means Box can hold any type, but we don't specify which yet. When we create instances like intBox and strBox, we replace <T> with Int and String respectively. The execution table traces each step: declaring the generic, creating instances with specific types, and accessing their stored values. The variable tracker shows how intBox and strBox hold different types safely. Key moments clarify why <T> is a placeholder and how it is replaced. The quiz tests understanding of when and how <T> is replaced and type safety. The snapshot summarizes the syntax and rules for generic type declaration in Swift.

Practice

(1/5)
1. What is the main purpose of using generic type declaration in Swift?
easy
A. To declare variables with fixed types only
B. To write flexible functions or types that can work with any data type
C. To create functions that only accept integers
D. To make code run faster by avoiding type checks

Solution

  1. Step 1: Understand generics concept

    Generics allow writing code that works with any type, not just one fixed type.
  2. Step 2: Compare options with concept

    Only To write flexible functions or types that can work with any data type describes this flexibility. Others limit types or mention speed, which is incorrect.
  3. Final Answer:

    To write flexible functions or types that can work with any data type -> Option B
  4. Quick Check:

    Generics = Flexible code for any type [OK]
Hint: Generics = code that works with any type [OK]
Common Mistakes:
  • Thinking generics fix types instead of generalizing
  • Confusing generics with performance optimization
  • Assuming generics only work with numbers
2. Which of the following is the correct syntax to declare a generic function in Swift?
easy
A. func swapValues(a: T, b: T) { let temp = a; a = b; b = temp }
B. func swapValues<T>(a: T, b: T) { let temp = a; a = b; b = temp }
C. func swapValues<T>(a: T, b: T) -> T { return a }
D. func swapValues<T>(a: inout T, b: inout T) { let temp = a; a = b; b = temp }

Solution

  1. Step 1: Identify correct generic syntax

    Generic functions use angle brackets <T> and parameters with inout to swap values.
  2. Step 2: Check each option

    func swapValues<T>(a: inout T, b: inout T) { let temp = a; a = b; b = temp } correctly uses func swapValues<T>(a: inout T, b: inout T) and swaps values. Others miss inout or have wrong return types.
  3. Final Answer:

    func swapValues<T>(a: inout T, b: inout T) { let temp = a; a = b; b = temp } -> Option D
  4. Quick Check:

    Generic function with inout parameters = func swapValues<T>(a: inout T, b: inout T) { let temp = a; a = b; b = temp } [OK]
Hint: Generic functions need <T> and inout for swapping [OK]
Common Mistakes:
  • Forgetting <T> after function name
  • Not using inout for parameters to modify them
  • Adding incorrect return types
3. What will be the output of this Swift code?
func printType<T>(_ value: T) {
    print("Type is: \(type(of: value))")
}
printType(42)
printType("Hello")
medium
A. Type is: Int\nType is: String
B. Type is: T\nType is: T
C. Type is: Any\nType is: Any
D. Type is: Optional<Int>\nType is: Optional<String>

Solution

  1. Step 1: Understand generic function behavior

    The function prints the actual type of the passed value using type(of:).
  2. Step 2: Analyze calls with 42 and "Hello"

    42 is an Int, "Hello" is a String, so output prints their types exactly.
  3. Final Answer:

    Type is: Int\nType is: String -> Option A
  4. Quick Check:

    type(of:) shows actual type = Type is: Int\nType is: String [OK]
Hint: type(of:) prints actual type, not generic placeholder [OK]
Common Mistakes:
  • Assuming generic type T prints literally
  • Confusing Any with specific types
  • Expecting Optional types without optionals
4. Identify the error in this generic struct declaration:
struct Box<T> {
    var value: T
    func printValue() {
        print(value)
    }
}

let box = Box(value: 5)
box.printValue()
medium
A. Missing generic type declaration after struct name
B. Cannot create instance without specifying type explicitly
C. No error; code compiles and prints 5
D. printValue() must be static to access value

Solution

  1. Step 1: Review struct and instance creation

    The struct declares generic type T correctly and has a property value of type T.
  2. Step 2: Check instance creation and method call

    Swift infers T as Int from 5. Calling printValue() prints 5 without error.
  3. Final Answer:

    No error; code compiles and prints 5 -> Option C
  4. Quick Check:

    Generic struct with inferred type works fine = No error; code compiles and prints 5 [OK]
Hint: Swift infers generic types from initializer values [OK]
Common Mistakes:
  • Thinking generic type must be explicitly stated
  • Assuming printValue() needs to be static
  • Believing missing syntax error in struct declaration
5. How can you declare a generic function in Swift that accepts two parameters of different types and returns a tuple of those types?
hard
A. func combine(_ a: T, _ b: U) -> (T, U) { return (a, b) }
B. func combine<T>(_ a: T, _ b: T) -> (T, T) { return (a, b) }
C. func combine(_ a: T, _ b: U) -> T { return a }
D. func combine(_ a: T, _ b: U) -> (U, T) { return (b, a) }

Solution

  1. Step 1: Understand requirement for two different generic types

    The function must accept two parameters of different types, so two generic placeholders T and U are needed.
  2. Step 2: Check return type as tuple of those types

    Return type should be (T, U) matching parameter order and types.
  3. Step 3: Verify options

    func combine(_ a: T, _ b: U) -> (T, U) { return (a, b) } matches all requirements. func combine<T>(_ a: T, _ b: T) -> (T, T) { return (a, b) } uses same type for both parameters. func combine(_ a: T, _ b: U) -> T { return a } returns only one type. func combine(_ a: T, _ b: U) -> (U, T) { return (b, a) } swaps tuple order, which is not asked.
  4. Final Answer:

    func combine<T, U>(_ a: T, _ b: U) -> (T, U) { return (a, b) } -> Option A
  5. Quick Check:

    Two generic types + tuple return = func combine<T, U>(_ a: T, _ b: U) -> (T, U) { return (a, b) } [OK]
Hint: Use two generic placeholders and tuple return type [OK]
Common Mistakes:
  • Using one generic type for both parameters
  • Returning only one value instead of tuple
  • Swapping tuple order incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard