Action methods with parameters

Hello,

So while watching the “String and Variables” tutorial in the course “Your First iOS App” I’ve encountered something which I don’t understand.

@IBAction func sliderMoved(_ slider: UISlider) {

}

or

@IBAction func sliderMoved() {

}

what would be the difference between these two action methods, except the one has parameters and one doesn’t, and if it affects the app in any way, why include it, and how Xcode/Swift knows how to fill-in this parameter

Thanks in advance

Shay.

Hi @shaypaustovsky9,
Let me first start with the @IBAction func, this is a way of indicating to Xcode that this is a UIKit event handler.

Next, the parameter for most of these handlers that comes from Objective-C where the parameter was of type id. Now with Swift, the handler can be both, with a parameter or without, where the parameter can be of type Any or a specific type. Most importantly, the parameter has an internal name not a parameter name.

The difference between using a parameter and not using a parameter are

  • If you already have an @IBOutlet to the element, then you can directly access properties whatever you want from the reference variable.
  • You could have say a couple of UIButtons and instead of creating several onPressed button actions, you could wire them all to the same @IBAction and then use the parameter to determine which button was pressed.

Hope that gives you a start,

cheers,

Jayant

Hi @jayantvarma,

First of all let me thank you for your support, I really do appreciate it.
Secondly so if I got the idea right, in objective-C you had (id) and in Swift it’s the “sender” parameter (the object that called the method) ?

Shay

Hi @shaypaustovsky9,
id in Objective-C is the equivalent to Any in Swift.

In Objective,

- (void) doSomething:(id) sender { } 

In Swift would look like

@IBAction func doSomething(_ sender: Any) { }

cheers,

Jayant

Hi @jayantvarma,

Now it all makes sense. I really do appreciate your support

Best Regards,
Shay

This topic was automatically closed after 166 days. New replies are no longer allowed.