What's the _ underscore representative of in Swift References?

Confused picture Confused · Jun 26, 2014 · Viewed 46.9k times · Source

In the reference section of Apple's docs there's lots of instances of this sort of thing:

func runAction(_action: SKAction!)

The Objective-C 'equivalent' of this is:

- (void)runAction:(SKAction *)action

It strikes me that it's probably important that (in the Swift reference) there's a space after the underscore and "action" is written in italics.

But I can't figure out what this is trying to convey. So perhaps the question is... is there a reference for the conventions used in the references?

-- here's the page I'm referencing in this reference to the underscore use: https://developer.apple.com/documentation/spritekit/sknode#//apple_ref/occ/instm/SKNode/runAction

Update

Swift 3 has made some changes to how function/method parameter names and argument labels are used and named. This has ramifications on this question and its answer. @Rickster does an amazing job of answering a different question about _underscores in functions that clears much of this up, here: Why do I need underscores in swift?

Answer

Aaron He picture Aaron He · Jun 27, 2014

Both answers were correct but I want to clarify a little bit more.

_ is used to modify external parameter name behavior for methods.

In Local and External Parameter Names for Methods section of the documentation, it says:

Swift gives the first parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local and external parameter names by default.

On the other hand, functions by default don't have external parameter names.

For example, we have this foo() method defined in class Bar:

class Bar{
    func foo(s1: String, s2: String) -> String {
        return s1 + s2;
    }
}

When you call foo(), it is called like bar.foo("Hello", s2: "World").

But, you can override this behavior by using _ in front of s2 where it's declared.

func foo(s1: String, _ s2: String) -> String{
    return s1 + s2;
}

Then, when you call foo, it could be simply called like bar.foo("Hello", "World") without the name of the second parameter.

Back to your case, runAction is a method because it's associated with type SKNode, obviously. Thus, putting a _ before parameter action allows you to call runAction without an external name.

Update for Swift 2.0

Function and method now work the same way in terms of local and external argument name declaration.

Functions are now called by using external parameter name by default, starting at 2nd parameter. This rule only applies to pure Swift code.

So, by providing an _ in front of a function, the caller won't have to specify external parameter name, just like what you would do for a method.