Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 510
Chanchal Chauhan Avatar asked Nov 15 '25 11:11

Chanchal Chauhan


2 Answers

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")
like image 177
Mukesh Avatar answered Nov 18 '25 07:11

Mukesh


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)
    }
}
like image 27
iParesh Avatar answered Nov 18 '25 05:11

iParesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!