From the course: Swift 5: Protocol-Oriented Programming
Unlock the full course today
Join today to access over 22,400 courses taught by industry experts or purchase this course individually.
Defining generic functions and methods
From the course: Swift 5: Protocol-Oriented Programming
Defining generic functions and methods
- [Instructor] Implementing a new function for every type leads to a lot of redundant code. To avoid code duplication, we can combine all the different functions into a single generic function. Let's see how. I create a new playground page called Using Generics. And let's rename the previous one too without generics. To create the gener, replace. To create the generic function, we need to provide at least one place holder type. The place holder type must appear right after the functions' name between angle brackets. So I declare the equals function and I provide the place holder type between angle brackets. We could have used any other identifier. Capital T is just a popular way to refer to generic place holders. We can use this place holder type in the argument list or anywhere in the functions body. So let's define the functions parameters. The left hand side argument of type T and right hand side also of type T,…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.