2

Today I opened my project in Xcode and it required to convert current Swift to Swift 3. After the conversion, I found all parameters of functions have an underscore in front. For example, func didGetWeather(_ weather: Weather) {}. I tried to take away the underscores and it worked fine. I wonder what those underscores are for.

2

3 Answers 3

4

Before swift3 the label of the first parameter by default was not listed in the function call, in swift3 does, the way to not name the parameters is placing an underscore before the parameter name in the signature, swift3 migrator add underscore the functions first parameter to not break existing code that rely on not placing the first label at function call.

Sign up to request clarification or add additional context in comments.

Comments

2

As per Apple documentation:

If you don’t want an argument label for a parameter, write an underscore (_) instead of an explicit argument label for that parameter.

func someFunction(_ firstParameterName: Int, secondParameterName: Int) { // In the function body, firstParameterName and secondParameterName // refer to the argument values for the first and second parameters. }

someFunction(1, secondParameterName: 2)

If a parameter has an argument label, the argument must be labeled when you call the function.

In Swift 2, we used to declare functions like:

func myFunc(param1 param:String) {}

and we had to call it like:

myFunc(param1:)

But later Apple introduced a way to omit argument labels using underscore(_), the function declaration would be:

func myFunc(_ param:String) {}

And then we can call the function in two ways:

myFunc(_:) // when we don't want to pass any parameters

Or

myFunc(param:"some string") // when we want to pass any parameters

The first way (using _) is mostly used when we want to define a selector. For eg:

someButton.addTarget(self, action: #selector(shareCatalog(_:)), for: .touchUpInside)

Comments

0

Yes, its changelog in Swift 3.0.

All function parameters have labels and "_" with at first of function :

Now below all default methods also have (_).

override func viewWillAppear(_ animated: Bool) override func didMoveToView(_ view: SKView) func textFieldShouldReturn(_ textField: UITextField) -> Bool 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.