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

What does operation(self) mean here?

extension String { func modify(operation: String -> String) -> String { return operation(self) } }

I am confused as to what the return statement is doing here. I see that operation is a function that takes a string and returns a string, but I don't understand what 'self' means i this context

1 Answer

As you probably know, 'String' in the Swift language is a struct. Since this extension is adding a function called 'modify' to the Swift String struct, the function 'modify' can only be called on instances of String using dot notation (as opposed to calling it on the class or just calling it on nothing). So the 'self' here refers to the instance of String on which the function is being called. The same would be true of any function that references 'self'. It always refers to the class or struct from which it is being referenced.

For example let's create a string:

var someString: String = "Hello"

Let's also create an empty string:

var modifiedString: String = ""

Now let's call the modify function on someString. Since modify takes a String -> String closure, let's pass one in that simply adds "!" to whatever String is passed in.

modifiedString = someString.modify {  (str) -> String in
    return str + "!" 
}

The part between the {} braces is the closure that is passed in to the 'modify' function. If you recall, this closure is passed in with the parameter name 'operation'. What happens next is that the modify function takes this closure (again, called 'operation' within the function declaration) and passes the parameter 'self' into it. In this case, that 'self' is the value of someString, since that is the variable that we called 'modify' on. The result is that the value of someString, which is "Hello" is passed in to the closure and an "!" is added to it. This final string is then returned and now the value of modifiedString is "Hello!".

I hope that helped... I'm not the best explainer so please let me know if I can clarify.