Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: difference between function calling

Tags:

ios

swift

iphone

I am novice in Swift programming. I am not able to understand following code. In following code to call

  1. incrementBy method: I must have to type numberOfTimes in second argument. But,
  2. 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.

like image 500
Umang Kothari Avatar asked Jan 08 '23 06:01

Umang Kothari


2 Answers

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.

like image 91
NSNoob Avatar answered Jan 17 '23 02:01

NSNoob


@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

like image 25
katleta3000 Avatar answered Jan 17 '23 04:01

katleta3000