Bird
Raised Fist0
Swiftprogramming~10 mins

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

Choose your learning style10 modes available
Concept Flow - Generic function declaration
Start
↓
Declare generic function with <T>
↓
Call function with specific type
↓
Function uses T as placeholder
↓
Function returns or processes T
↓
End
This flow shows how a generic function is declared with a placeholder type T, then called with a specific type, and how T is used inside the function.
Execution Sample
Swift
func echo<T>(value: T) -> T {
    return value
}

let result = echo(value: 42)
This code declares a generic function echo that returns the same value it receives, then calls it with an integer 42.
Execution Table
StepActionGeneric Type TInput valueReturn value
1Function echo<T> declaredT is a placeholderN/AN/A
2Call echo with value 42T inferred as Int42N/A
3Inside echo, return valueT = Int4242
4Assign return to resultT = Int4242
5EndN/AN/AN/A
💡 Function completes after returning the input value as output.
Variable Tracker
VariableStartAfter callFinal
valueN/A4242
resultN/AN/A42
TPlaceholderIntInt
Key Moments - 3 Insights
Why do we write <T> after the function name?
The <T> declares a placeholder type that the function can use for any type. See execution_table step 1 where T is a placeholder.
How does the function know what type T is when called?
The compiler infers T from the argument type when the function is called, as shown in execution_table step 2 where T is inferred as Int.
Can the function return a different type than the input?
In this example, the function returns the same type T it receives, so input and output types match, as seen in step 3 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the type of T when echo is called with 42?
AString
BDouble
CInt
DPlaceholder only, no type yet
💡 Hint
Check execution_table step 2 where T is inferred as Int.
At which step does the function return the input value?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at execution_table step 3 where return value is 42.
If we call echo with a String instead of Int, what changes in variable_tracker?
AT stays Int, value and result become String
BT changes to String, value and result become String
CT stays placeholder, no change
DFunction will not compile
💡 Hint
Generic type T adapts to input type, see variable_tracker for T and value.
Concept Snapshot
Generic function syntax:
func functionName<T>(param: T) -> T {
    // use T as type
}

- <T> declares a placeholder type.
- T is inferred from arguments when called.
- Allows writing flexible, reusable functions.
Full Transcript
This visual execution traces a generic function declaration in Swift. The function echo<T> is declared with a generic type T as a placeholder. When called with the integer 42, the compiler infers T as Int. Inside the function, the input value is returned as output, preserving the type. Variables value and result track the input and output values. Key moments clarify why <T> is used, how T is inferred, and that input and output types match. The quiz tests understanding of type inference, return step, and behavior with different input types.

Practice

(1/5)
1. What is the purpose of declaring a generic function in Swift using <T>?
easy
A. To allow the function to work with any data type without rewriting code
B. To restrict the function to only work with integers
C. To make the function run faster by using a specific type
D. To create a function that only works with strings

Solution

  1. Step 1: Understand generic function purpose

    Generic functions use placeholders like <T> to accept any data type.
  2. Step 2: Analyze options

    Only To allow the function to work with any data type without rewriting code correctly states that generics allow code reuse for many types without rewriting.
  3. Final Answer:

    To allow the function to work with any data type without rewriting code -> Option A
  4. Quick Check:

    Generic functions = flexible type use [OK]
Hint: Generics mean one function fits many types [OK]
Common Mistakes:
  • Thinking generics limit types instead of generalizing
  • Confusing generics with type-specific functions
  • Assuming generics improve speed directly
2. Which of the following is the correct syntax to declare a generic function named swapValues in Swift?
easy
A. func swapValues(a: T, b: T) { }
B. func swapValues<T>(a: Int, b: Int) { }
C. func swapValues<T>(a: T, b: T) { }
D. func swapValues(a: T, b: U) { }

Solution

  1. Step 1: Identify correct generic syntax

    Generic functions declare type placeholders inside angle brackets after the function name, like <T>.
  2. Step 2: Check parameter types

    func swapValues<T>(a: T, b: T) { } correctly uses <T> and parameters of type T. func swapValues(a: T, b: T) { } misses <T>. func swapValues<T>(a: Int, b: Int) { } uses Int which is not generic. func swapValues(a: T, b: U) { } uses two generic types but swap usually uses one.
  3. Final Answer:

    func swapValues<T>(a: T, b: T) { } -> Option C
  4. Quick Check:

    Generic syntax = func name<T>(...) [OK]
Hint: Generic type <T> goes right after function name [OK]
Common Mistakes:
  • Forgetting <T> after function name
  • Using concrete types instead of generic placeholders
  • Mixing multiple generic types unnecessarily
3. What will be the output of the following Swift code?
func printValue<T>(value: T) {
    print("Value is \(value)")
}
printValue(value: 42)
printValue(value: "Hello")
medium
A. Compilation error due to type mismatch
B. Value is 42\nValue is Hello
C. Value is Hello\nValue is Hello
D. Value is 42\nValue is 42

Solution

  1. Step 1: Understand generic function behavior

    The function printValue accepts any type T and prints it.
  2. Step 2: Analyze calls with different types

    First call passes an integer 42, second passes a string "Hello". Both print correctly.
  3. Final Answer:

    Value is 42 Value is Hello -> Option B
  4. Quick Check:

    Generic function prints any type value [OK]
Hint: Generic functions accept any type without error [OK]
Common Mistakes:
  • Assuming generic functions only accept one type per program
  • Expecting type mismatch error for different calls
  • Confusing output order
4. Identify the error in this generic function declaration and fix it:
func compareValues<T>(a: T, b: T) -> Bool {
    return a > b
}
medium
A. Remove generic and use Int type instead
B. No error, function is correct
C. Change return type to Int
D. Add constraint: to allow '>' operator

Solution

  1. Step 1: Understand operator usage in generics

    The '>' operator requires the type to conform to Comparable protocol.
  2. Step 2: Add constraint to generic type

    Adding <T: Comparable> ensures T supports '>' operator.
  3. Final Answer:

    Add constraint: <T: Comparable> to allow '>' operator -> Option D
  4. Quick Check:

    Generic constraints needed for operators [OK]
Hint: Use when comparing generics [OK]
Common Mistakes:
  • Ignoring protocol constraints for operators
  • Changing return type unnecessarily
  • Removing generics instead of fixing constraints
5. You want to write a generic function findFirstIndex that returns the first index of a value in an array. Which declaration correctly uses generics and constraints to achieve this?
hard
A. func findFirstIndex(array: [T], value: T) -> Int? { for (index, element) in array.enumerated() { if element == value { return index } } return nil }
B. func findFirstIndex<T>(array: [T], value: T) -> Int? { for (index, element) in array.enumerated() { if element == value { return index } } return nil }
C. func findFirstIndex(array: [Int], value: Int) -> Int? { for (index, element) in array.enumerated() { if element == value { return index } } return nil }
D. func findFirstIndex(array: [T], value: T) -> Int? { for (index, element) in array.enumerated() { if element == value { return index } } return nil }

Solution

  1. Step 1: Understand equality requirement

    To compare elements with '==', type T must conform to Equatable.
  2. Step 2: Check generic constraints and function logic

    func findFirstIndex(array: [T], value: T) -> Int? { for (index, element) in array.enumerated() { if element == value { return index } } return nil } correctly declares T: Equatable and uses a loop to find the first matching index.
  3. Final Answer:

    func findFirstIndex<T: Equatable>(array: [T], value: T) -> Int? { ... } -> Option A
  4. Quick Check:

    Equality check needs Equatable constraint [OK]
Hint: Use when checking equality in generics [OK]
Common Mistakes:
  • Omitting Equatable constraint causing compile error
  • Using Comparable instead of Equatable unnecessarily
  • Restricting to Int instead of generic type
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