Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,504 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,371 Points

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