0
0
Swiftprogramming~5 mins

Generic function declaration in Swift

Choose your learning style9 modes available
Introduction

Generic functions let you write one function that works with many types. This saves time and avoids repeating code.

When you want a function to work with different types like numbers, strings, or custom objects.
When you want to create reusable code that can handle many data types safely.
When you want to avoid writing the same function multiple times for different types.
Syntax
Swift
func functionName<T>(parameter: T) -> T {
    // function body
}

The <T> after the function name declares a generic type called T.

You can use T as a placeholder for any type inside the function.

Examples
This function returns whatever value it receives, no matter the type.
Swift
func echo<T>(value: T) -> T {
    return value
}
This function swaps two values of the same type using generic type T.
Swift
func swapValues<T>(a: inout T, b: inout T) {
    let temp = a
    a = b
    b = temp
}
Sample Program

This program defines a generic function that prints any item twice. It works with a string and an integer.

Swift
func printTwice<T>(item: T) {
    print(item)
    print(item)
}

printTwice(item: "Hello")
printTwice(item: 42)
OutputSuccess
Important Notes

Generic functions help keep your code clean and flexible.

You can use any name instead of T, but T is a common convention.

Summary

Generic functions use placeholders for types to work with many data types.

They help avoid repeating similar code for different types.

Use <T> syntax to declare generic functions in Swift.