0

I'm new to Swift and I've read the Swift Function Documentation and as far as I understand a function has to be built this way:

func funcName(param1:Type, param2:Type) -> Return {
    //Whatever istructions
}

And has to be called this way:

funcName(1, 2);

Very easy, and here is from the original Apple documentation:

func halfOpenRangeLength(start: Int, end: Int) -> Int {
    return end - start
}

println(halfOpenRangeLength(1, 10))
// prints "9"

So in this last example when calling the halfOpenRangeLength function I don't have to specify the name of the parameters (start and end).

So I did my function in XCode:

func assegnaRisposte(uno:String, due:String, tre:String, quattro:String){
    button1.setTitle(uno, forState: UIControlState.Normal)
    button2.setTitle(due, forState: UIControlState.Normal)
    button3.setTitle(tre, forState: UIControlState.Normal)
    button4.setTitle(quattro, forState: UIControlState.Normal)
}

But when I call it this way I get the error Missing argument lables 'due:tre:quattro:' in call:

assegnaRisposte("Davide", "Andrea", "Sergio", "Roberto")

And the XCode fix imposes me to do it this way:

assegnaRisposte("Davide", due: tre: "Andrea", "Sergio", quattro: "Roberto")

So I'M FORCED to place 3 of the parameter names. If I place the first parameter (uno) it throws an error, so I have to put ONLY due, tre and quattro

As far as I read I can specify the parameter names placing a dash in front of the parameter, and also, I'm not FORCED to use them.

Can somebody explain me why is this?

Mr.Web
  • 6,992
  • 8
  • 51
  • 86

2 Answers2

2

There is a difference between functions and methods in Swift in naming, basically:

  • the default naming of functions is that there are no external parameter names.
  • the default naming for methods is that there are external parameter names expect the first parameter.

And you can read about the differences between methods and functions here or here.

Updated:

If you don't want to use external parameter names, you should declare your method like:

func assegnaRisposte(uno:String, _ due:String, _ tre:String, _ quattro:String){
...
}
Community
  • 1
  • 1
Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58
0

Check out this section from Apple's The Swift Programming Language book:

Local and External Parameter Names for Methods

The default behavior of local names and external names is different for functions and methods.

Swift gives the first parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local and external parameter names by default.

Salavat Khanov
  • 4,100
  • 2
  • 15
  • 27