2

In swift why must you pass in the first argument value without writing its name, and every subsequent value with its name when calling a function like so:

func greet(name: String, day: String) -> String {
    return "Hello \(name), today is \(day)."
}

greet("Anna", day: "Tuesday")
rigdonmr
  • 2,662
  • 3
  • 26
  • 40
  • 1
    Possible duplicate of [Why does a function call require the parameter name in Swift?](http://stackoverflow.com/questions/24045890/why-does-a-function-call-require-the-parameter-name-in-swift) – Eric Aya Jan 08 '16 at 09:36
  • This line style naming methods from Objective C when you can read it lieke: `getName(name, fromPerson: person, withAge: age)` – Alexey Pichukov Jan 08 '16 at 09:36
  • If you want to not write out day, you could change the declaration to `greet(name: String, _ day: String) -> String` – TPlet Jan 08 '16 at 09:38
  • @EricD. Not a duplicate because I'm specifically asking why you don't use the parameter name *only for the first* but not the subsequent ones. – rigdonmr Jan 08 '16 at 09:39
  • No problem, I've retracted my vote to close as dupe since it's not an exact duplicate and you got a nice answer anyway. – Eric Aya Jan 08 '16 at 10:03

1 Answers1

6

Because the naming convention for Objective-C (see here) and Swift is to end your method name by the name of your first argument:

func greetPersonNamed(name: String, onDay day: String) -> String {
    return "Hello \(name), today is \(day)."
}

greetPersonNamed("Anna", onDay: "Tuesday")

If you prefer to write the name of the first argument, you can do it like so:

func greet(name name: String, day: String) -> String { /* ... */ }
greet(name: "Anna", day: "Tuesday")

The first name refers to the external name, the second one is the one used inside your method.

EDIT

The naming guidelines for Swift 3 have been released (see here) and they differ from the ones used with Objective-C.

The name of the first argument should not be included in the method name. The external name of the first parameter can be omitted if the function intent is clear. Otherwise you should name it.

Let's say you can greet persons and pets. In that case, you should add an external name for the first argument:

func greet(person name: String, day: String)
func greet(pet name: String, day: String)

greet(person: "Anna", day: "Tuesday")

If you can only greet persons, then you can ommit it:

func greet(name: String, day: String)
greet("Anna", day: "Tuesday")
Raphaël
  • 3,646
  • 27
  • 28
  • I actually can't tell you how much this answer has helped. Built in Swift variable names make so much more sense now... – rigdonmr Jan 09 '16 at 04:24