swiftfunctionibaction

What is the purpose of under score in when declaring a IBAction func?


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?


Solution

  • 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