Alex Alex - 4 months ago 7x
Swift Question

What is _: in Swift telling me?

What does the lone underscore mean in function definitions?



I understand that when defining functions I can do:

func myFunc(_ string: String) { ... }

Would I then refer to that as
instead of
, i.e. purposefully hiding the parameter name?


Swift needs a convention for saying what the name of a function is, including not only the function name itself (before the parentheses) but also the external names of the parameters. The convention is that the names are followed by colons. So here's a function declaration (in Swift 2.0):

func myFunc(param1 param1:String, param2:String, param3:String) {}

And here is that function's name:


In real life, however, it is possible (indeed likely) that one or more parameters will not externalize any name. Thus we need a placeholder for that name. The underscore is that placeholder - just as the underscore is the symbol in the declaration suppressing externalization of the name. So, here's another function declaration (in Swift 2.0):

func myFunc2(param1:String, _ param2:String, _ param3:String) {}

And here is that function's name:


[The Swift 2.0 spec is important here. In Swift 2.0, the first param name is always not externalized by default, and the other param names are externalized by default. In Swift 1.2 and before, the externalization rules depended on where the declaration appeared, which was unnecessarily inconsistent and confusing.]