Chanchal Chauhan
Chanchal Chauhan

Reputation: 1560

Error while using default value in parameter of Protocol's method

I have a method in Protocol and using this method so many times. Now I need to add one more parameter in that method. I just need to pass that parameter in one case. So I have added default value in that parameter. But protocol doesn't accept default value. So what I did is:

protocol TestP {
    func update(srId: String, srType: String? )
}

class Test: TestP {
    func update(srId: String, srType: String? = "") {
        print("abc")
    }
}

let test: TestP = Test()
test.update(srId: "abc")

But here I am getting error error: missing argument for parameter 'srType' in call because at compile time it check method in Protocol and do not find default value for srType. So I try adding same method in extension of Protocol as given:

extension TestP {
    func update(srId: String, srType: String? = "") {
        print("abc")
    }
}

Here class Test method should be called because the object is of class Test. But every time protocol's method is being called. I don't know what is wrong with my code? How can I do that?

Upvotes: 4

Views: 1459

Answers (2)

Mukesh
Mukesh

Reputation: 2902

I would suggest you to use following method signature:

extension TestP {
    func update(srId: String) {
        update(srId: srId, srType: "")
    }
}

Because if you want to pass srType in the call you already have the method func update(srId: String, srType: String?) in the protocol.

There is no need to use parameter with default value.

Call with default value:

let test: TestP = Test()
test.update(srId: "abc")

Call with srType parameter:

let test: TestP = Test()
test.update(srId: "abc", srType: "type")

Upvotes: 4

iParesh
iParesh

Reputation: 2368

Update protocol extension with below code

Extension provides the default values, calling original protocol function with those default values

extension TestP {
    func update(srId: String, srType: String? = "") {
        update(srId: srId, srType: srType)
    }
}

Upvotes: 3

Related Questions