Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Closures Functions as First Class Citizens Capturing Variables

Explain this code

func makeIncrementer(forIncrement amount: Int) -> () -> Int {

I beg someone explain this to me. Why so much Ints and arrows...?

3 Answers

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Antonija,

This looks intimidating, but if we break it down, it's not too bad. I think there's probably only one or two concepts in here you might not be familiar with.

The basic syntax of declaring a function is func [the name of the function] ([parameter(s)])->[return type] { [body of the function] }. You probably know that.

Let's start with the parameters: the first concept you might not be familiar with is a named parameter. This function takes a parameter, amount, which is of type Int, and which is named forIncrement. This means that when you call the function you would include the name of the parameter, and then the parameter itself, like this: makeIncrementer(forIncrement: 25);. The Swift compiler would require an integer because of that first Int.

Now for the return type. Just like always, everything between the -> and the { is the return type. In this case we have ()->Int. That kind of looks like its own function definition, doesn't it? In fact that's pretty much exactly what it is; this means that the function returns another function. Crazy, right? Anyway, it returns a function, and that function returns an integer, so that's the reason for the second Int.

So in summary, this is a function that takes a single integer as a parameter, and returns a function which itself will return an integer.

Sort of confusing, but not too bad, right?

Let me know if this makes sense!

Best,

-Greg

Hi Greg,

the first part was fine but the second blew my brain. I am still struggling to "visualise" this in my brain and I am having a hard time with it. I will live this as is for now, but I will come back and try to understand it 100%.

Thanks.

Greg Kaleka
Greg Kaleka
39,021 Points

Hah understandable. The basic idea is simply that the return type is a function. This is a pretty advanced topic, so no worries if you don't totally grasp it yet!

thomas lotocki
thomas lotocki
3,230 Points

One might ask why would you do that?