Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources
Generic Functions in Swift

Generic Functions in Swift

Introduction to Generics

Generics are a powerful feature in Swift that allows you to write flexible and reusable code. With generics, you can create functions and types that can work with any data type. This means you can write code that is type-safe and can handle a variety of data, all while maintaining performance and clarity.

What are Generic Functions?

A generic function is a function that can operate on different data types without being rewritten for each type. Instead of specifying a particular type, you define a placeholder, known as a type parameter, which is then substituted with a concrete type when the function is called.

Defining a Generic Function

To define a generic function, you use angle brackets (<>) to declare the type parameter. Here's a simple example of a generic function that swaps two values:

func swap<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}

In this example, T is the type parameter that can represent any type. The function takes two parameters of type T and swaps their values.

Using a Generic Function

You can call the generic function with any data type. Here's how you can use the swap function:

var a = 5
var b = 10
swap(&a, &b)
print("a: \\(a), b: \\(b)")
Output: a: 10, b: 5

In this case, a and b are integers, and after calling swap, their values are swapped.

Generic Constraints

Sometimes, you may want to restrict the types that can be used with a generic function. This is done using generic constraints. For example, if you want to create a function that only works with types that conform to the Comparable protocol (such as Int, String, etc.), you can define it like this:

func findMax<T: Comparable>(_ a: T, _ b: T) -> T {
return a > b ? a : b
}

Here, the function findMax takes two parameters of any type T that conforms to Comparable and returns the maximum of the two.

Using Generic Constraints

You can use the findMax function with various types that conform to Comparable:

let maxInt = findMax(5, 10)
let maxString = findMax("apple", "banana")
print("Max Int: \\(maxInt)")
print("Max String: \\(maxString)")
Output: Max Int: 10, Max String: banana

Conclusion

Generic functions in Swift provide a way to write flexible and reusable code. By using type parameters and constraints, you can create powerful functions that work with any data type while ensuring type safety. This feature is essential for writing clean and efficient code in Swift.