1

Beginner question, I realise that when the Xcode declares a function for @IBAction, it declares it as below:

@IBAction func hardnessSelected(_ sender: UIButton), which I read is,

Create a function called hardness selected which accepts a parameter called sender which accepts the type UI button.

From my understanding so far _ is used when you want to declare a variable that you are not going to mutate e.g. in a for loop to tell swift the value of this variable doesn't matter to optimize performance.

However, in the above case there is a name for the variable "sender" as well as _ which I don't understand why.

Can someone please explain?

Alexander
  • 59,041
  • 12
  • 98
  • 151
djumanji
  • 43
  • 5
  • 1
    underscore allows you to omit the parameter name when calling the method `hardnessSelected(aButton)`instead of `hardnessSelected(sender: aButton)` – Leo Dabus Jun 07 '21 at 22:49
  • 1
    Please see “omitting argument labels” on https://docs.swift.org/swift-book/LanguageGuide/Functions.html – Alexander Jun 07 '21 at 22:55

2 Answers2

1

This place is declared for the label which means that once you call the function it won't appear to you for example:

   func sum (_ number1: Int, _ number2: Int) {
    print(number1 + number2)
}

once you call the function you won't need to mention number1 or number2 but you will only write the number directly :

sum(1, 2)

To be clear it's the same as using the function below:

func summation(myFirstNumber number1: Int, mySecondNumber number2: Int) {
    print (number1 + number2)
}

but here instead of using _ I've used a label so when I called the function, I will use these labels :

summation(myFirstNumber: 1, mySecondNumber: 2)

So it's clear now that _ is instead of writing a label.

For more information check: Function Argument Labels and Parameter Names from here

Menaim
  • 937
  • 7
  • 28
1

Swift allows having an argumentLabel different than actual argument itself for better readability.


In case your function signature is like this -

func value(for key: String)

In this case, these values are argumentLabel == for & argument == key. At the call site, you have to mention the argumentLabel like following.

value(for: "myCustomKey")

In case your function signature is like this -

func valueForKey(_ key: String)

In this case you are explicitly asking compiler to allow you to omit argumentLabel while calling this function. Please note that argument == key will not be visible at call site for this like following.

valueForKey("myCustomKey")

Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30