From the course: Swift 5: Protocol-Oriented Programming
Unlock the full course today
Join today to access over 22,600 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.
Contents
-
-
-
-
-
(Locked)
The importance of generics3m 12s
-
(Locked)
Defining generic functions and methods3m 32s
-
(Locked)
Working with generic types3m 29s
-
(Locked)
Placeholder types in protocols1m 54s
-
(Locked)
Using generics with protocols1m 45s
-
(Locked)
Challenge: Implementing a generic stack1m 21s
-
(Locked)
Solution: Implementing a generic stack6m 45s
-
(Locked)
-
-