Swift Generic Functions Tutorial 🎯

beginner
14 min

Swift Generic Functions Tutorial 🎯

Welcome back to CodeYourCraft! Today, we're diving into a powerful feature of Swift - Generic Functions. These functions allow you to write reusable code that works with different types.

What are Generic Functions? 📝

Generic functions are functions that can work with multiple data types. Instead of being tied to a specific type, they can accept any type you pass to them. This makes them incredibly versatile and a great tool for writing efficient and reusable code.

Why Use Generic Functions? 💡

  • Reusability: By not being tied to a specific type, generic functions can be used in many different contexts.
  • Efficiency: Generic functions can help reduce code duplication, making your code cleaner and more efficient.
  • Type Safety: Swift's type system ensures that the types you pass to a generic function are used correctly.

Writing a Simple Generic Function 🎯

Let's start by writing a simple generic function that calculates the sum of two values.

swift
func sum<T>(a: T, b: T) -> T { return a + b }

In this example, T is a placeholder for any type. The function takes two arguments of the same type T and returns a value of the same type. The -> T part specifies that the function returns a value of type T.

Using the Generic Function 🎯

You can use this generic function with any type, as shown below:

swift
let intSum = sum(a: 5, b: 7) let stringSum = sum(a: "Hello", b: "World")

In the first call, we're passing integers, and in the second call, we're passing strings. The function correctly calculates the sum for both cases.

Generic Function Types 📝

In Swift, you can use the following types as the placeholder T:

  • Int
  • Double
  • String
  • Array
  • Dictionary
  • Optional
  • Custom types

Quiz Time 🎯

Quick Quiz
Question 1 of 1

Which of the following is not a valid placeholder for a generic function in Swift?

Stay tuned for more on Swift Generic Functions! In the next lesson, we'll dive deeper and learn how to work with constraints and default values in generic functions.

Happy coding! 💻📚