Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Generics in Swift Generic Functions, Parameters and Constraints Multiple Type Parameters

transform function does the same thing as stringToInt or intToString

So in this video pasan makes a function called transform that transforms one type to the other. Well, to me it seems a little redundant to do that since the function he creates below this do this without the transform function.

2 Answers

Will Matthews
Will Matthews
8,127 Points

In the example, the transform function is actually only applying a given function "operation" to a given argument "arg". The transform function itself isn't really doing the heavy lifting, that's left to the function that's passed into it.

What this example is meant to highlight is that using generics as we have in the transform function allows us to clearly define a set of rules and type safety without having to be specific about what type or what function will be provided up front. All the transform function does is says, "I'm going to accept two things...a value and a function, and I'm going to spit out a result. However, that function that I'm accepting needs to itself accept an argument that's the same type as the value I've accepted, and will spit out something of the same type that I'll be spitting out."

So the benefit of this is that transform doesn't need to know specifically what types are being passed into it. Because this is just a simplified first step of an example, the real power of these generics may not be obvious yet. But as we get more experienced with these, and use more complex examples, their benefits should become more clear.

Does that make any more sense?

Bankole Abawonse
Bankole Abawonse
9,021 Points

I was of the same opinion as them, but your explanation made things a lot clearer. Thanks a lot!

Abdullah Althobetey
Abdullah Althobetey
18,216 Points

You are right. I too think the technique shown in the video is useless. Maybe Mr. Pasan shows us this technique merely to understand generics better.