0

The book that I'm currently reading on the topic of Swift Game Development references Swift functions without the first parameter and instead uses an underscore like so....

URLForResource(_, withExtension)

In actual code samples the underscore is replaced by a value, but when just referring to that function it is written as above. I've also seen it written this way in Apple documentation.

I just don't understand why the underscore is there. If this is the way you refer to a certain function, then how is the user supposed to know what kind of value goes in place of the underscore?

I have read that the first parameter in the function doesn't have to have an outside name, and that's fine, but leaving out the first parameter seems like it would cause the extra step of having to look up the function to see what parameter to pass there.

Would love if it if someone could clear this up for me. Thanks

ALTVisual
  • 116
  • 10
  • Having looked through the duplicate answers, I can say that there really isn't a good answer for this. Explaining what the underscore does is straight forward enough, but I've really yet to find any reason WHY it's used like this when referencing a function in documentation. I understand that it's not an external parameter, but writing it with an underscore, especially in documentation simply means that you can't look at the function and know the type of the first parameter. And if the first parameter is discarded then why represent it with anything? – ALTVisual Oct 13 '15 at 04:42

1 Answers1

2

So, you would just use the underscore if you don't want the user to have to input the name of the variable. For instance func foo(x: Int, y: Int) is called foo(6, y: 10) so if you didn't want whoever is calling the function to have to write the y you would create the function as func foo(x: Int, _ y: Int). Furthermore, if you wanted the called to have to write x and y, you would write func foo(x x: Int, y: Int). All of this is stylistic. Therefore, I would just do what makes sense. In xCode, there is obviously autocomplete so I always just leave the parameter names in because that makes the code clearer. So, there is no real point to having the underscore or function variable names other than making your code easier to understand.

Anthony Dito
  • 3,610
  • 3
  • 29
  • 56