Umang Kothari
Umang Kothari

Reputation: 3694

Swift: to call function seems confusing

I have copied following code snippets from developer site of apple.

  1. Following code works as expectation:

    func greet(day: String) -> String {
        return "Hello Umang, today is \(day)."
    }
    print(greet("Sunday"))
    
  2. While running following code showing error,

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

    Error:

    <stdin>:7:12: error: extraneous argument label 'day:' in call
    print(greet(day : "Sunday"))
    ^~~~~~~
    

I am novice in Swift programming, I have background in Java. So I am facing problem in understanding.

Please guide me if anything I have misunderstood.

Upvotes: 0

Views: 75

Answers (1)

Sandeep
Sandeep

Reputation: 21134

It is because first argument in a method is treated as unnamed parameter. So, you can only use greet("Sunday") but if you want your first argument to be a named parameter, you can use the following syntax.

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

Notice, the day is name for the parameter day.

Now, you can use it as,

print(greet(day : "Sunday"))

Upvotes: 4

Related Questions