I am novice in Swift programming. I am not able to understand following code. In following code to call
sampleFunc method: I must not have to type lastName in second argument.
class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes : Int) {
count += amount * numberOfTimes
}
}
var counter = Counter()
counter.incrementBy(1, numberOfTimes : 3)
print(counter.count)
func sampleFunc(firstName : String, lastName : String){
print("Hello \(firstName) \(lastName)")
}
sampleFunc("Abel", "Rosnoski")
Why is there subtle difference? Please explain.
When encapsulated in a class (or struct or enum), the first parameter name of a method is not included externally, while all following parameter names are included externally. The parameters which are not included externally, you don't have to give names for them when calling the method. But for externally included ones you have to.
Your method incrementBy(amount: Int, numberOfTimes : Int)
is encapsulated in your class that's why the second parameter is automatically externally included. Which means you have to type numberOfTimes
before providing value to parameter. That's why you must call it like:
counter.incrementBy(1, numberOfTimes : 3)
Your second method func sampleFunc(firstName : String, lastName : String)
is not enclosed in your class. That's why you don't have to provide name for its parameters. Which is why you can call it like:
sampleFunc("Abel", "Rosnoski")
You can read more details here.
Edit: As User3441734 kindly pointed out (And I quote) "There is one exception. init with parameters always requires named parameter, if the external name is not specified as _ ". You can read more about Customizing initialization here.
@NSNoob made a nice explanation, I just added some examples to understand power of function calls:
func sampleFunc(firstName : String, lastName : String) {}
sampleFunc("First", lastName: "Last")
You can remove naming second param like this:
func sampleFunc(firstName : String, _ lastName : String) {}
sampleFunc("First", "Last")
If you want to add naming for all params:
func sampleFunc(firstName firstName : String, lastName : String) {}
sampleFunc(firstName: "First", lastName: "Last")
If you want to make default value for param:
func sampleFunc(firstName firstName : String, lastName : String = "Last") {}
sampleFunc(firstName: "First")
Hope that helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With