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.
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.
Let's start by writing a simple generic function that calculates the sum of two values.
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.
You can use this generic function with any type, as shown below:
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.
In Swift, you can use the following types as the placeholder T:
IntDoubleStringArrayDictionaryOptionalWhich 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! 💻📚