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
Cobie Fisher
4,555 Points#Swift Why is the second parameter (in a function) in a string necessary and the first one isn't when calling?
In Xcode, why is it that when calling a function with parameters you need to put the parameter name before the second one and not the first one.
i.e. func test(a: String, b:String) -> String { return ("(a) + (b) = (a+b)") }
test("One", b: "Two")
Why is that "b" necessary if "a" isn't? I feel like this is one of those things that was a bug and then Apple decided to call it a "feature" or does it have an actual use?
1 Answer
Jhoan Arango
14,575 PointsHello:
They do this so that you can write comprehensive code, and it's easier to read.
Functions have parameters, which you can name. Each parameter can have a local and external parameter name, a "local parameter name" is used for the implementation of the function, and the "external parameter name" is used to label arguments passed to a function call. The first parameter will always omit its "external parameter name", meaning that when you call the function, you don't need to use it. But the second and subsequent parameters will use their "local parameter name" as their external.
For example:
func incrementBy(amount: Int) {}
When calling this function, you call it like this :
incrementBy(5)
// When you read this function, it makes sense right ?
But if we have a second parameter, we can name it depending on the functions needs.
func incrementBy(amount: Int, numberOfTimes: Int)
// We can call this function like this
incrementBy(5, numberOfTimes: 10)
You don't even know the implementation of this function, and you don't know how it will calculate its results, but by the names you can already assume that it will increment 5 by 10 times, giving you a result of 50.
Hopefully my answer helps with your question.
Good luck.
Cobie Fisher
4,555 PointsCobie Fisher
4,555 PointsThanks!