Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift Delegate Syntax

I'm new to iOS and Swift. I'm having a problem understanding the syntax used in Protocol methods used in Delegates. As an example, the following two methods used in the UIPickerView:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return count
}

The first method is fine but the syntax of the second method confuses me. The format of the second parameter is baffling, as far as I understand it this should be an Int called "component", so why does the action name "numberOfRowsInComponent" precede it?

Also why are the delegate methods all called "pickerView", are they all just overloads?

Any guidance would be appreciated.

like image 441
Ian Holtham Avatar asked Apr 01 '26 19:04

Ian Holtham


1 Answers

The full method name is pickerView:numberOfRowsInComponent but the component is the parameter name that will actually contain passed value

Read about External Parameter Names

Sometimes it’s useful to name each parameter when you call a function, to indicate the purpose of each argument you pass to the function.

If you want users of your function to provide parameter names when they call your function, define an external parameter name for each parameter, in addition to the local parameter name. You write an external parameter name before the local parameter name it supports, separated by a space:

func someFunction(externalParameterName localParameterName: Int) {
    // function body goes here, and can use localParameterName
    // to refer to the argument value for that parameter
}
like image 105
Azat Avatar answered Apr 03 '26 08:04

Azat