What if you could write one function that magically works for all your data types?
Why Generic function declaration in Swift? - Purpose & Use Cases
Imagine you need to write several functions that do the same thing but for different types of data, like numbers, strings, or custom objects. You end up copying and changing code many times.
This manual way is slow and boring. It's easy to make mistakes when copying code. Also, if you want to fix a bug or add a feature, you must update every copy separately, which wastes time and causes errors.
Generic function declaration lets you write one function that works with any type. You write the logic once, and it adapts to different data types automatically. This saves time and keeps your code clean and safe.
func swapInts(a: inout Int, b: inout Int) { let temp = a; a = b; b = temp }
func swapStrings(a: inout String, b: inout String) { let temp = a; a = b; b = temp }func swapValues<T>(a: inout T, b: inout T) { let temp = a; a = b; b = temp }It enables you to write flexible, reusable functions that work with any data type without repeating code.
Think about a function that sorts a list. With generics, you write it once, and it can sort numbers, names, or any custom objects you create.
Writing separate functions for each type is slow and error-prone.
Generic functions let you write one adaptable function for many types.
This makes your code cleaner, safer, and easier to maintain.