Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Protocols in Swift Protocol Basics Why Are Protocols Useful?

deepak sharma
deepak sharma
3,844 Points

in this video two function with same???

this is first funcion

func pay() -> PayCheck { return PayCheck(base: 0, benefits: 0, deductions: 0, vacation: 0) }

and this is second function??? func pay(employee: Employee) {

}

this is very confusing...how this is possible two func with same name?

2 Answers

andren
andren
28,558 Points

It's called function/method overloading and it is possible because they have different parameters defined. When you call a function Swift does not just look at the name of the function, but also at what arguments you are providing to it. Both the name and the arguments have to match for a function to be called.

So the first pay function defined in your example could only be called like this:

Pay() // Pay call with no arguments

While the second function would have to look something like this:

Pay(employee: someEmployee) // Pay with one argument which is called employee

Since it's possible to distinguish which function each call is intended for it's not a problem that multiple functions share the same name. This is actually a pretty common practice, not just in Swift but in many other Object Oriented Languages like Java, C++ and C#

deepak sharma
deepak sharma
3,844 Points

thanks andren, for explaining so nice...

Christopher Debove
Christopher Debove
Courses Plus Student 18,373 Points

It was already thoroughly explained in the chapter on Enumerations (examples with Day and DayType enums)