stevenpcurtis
stevenpcurtis

Reputation: 2001

Alternative to default argument in a protocol Swift

I understand that a default argument is not permitted in a protocol, meaning that the following is not valid:

protocol testProtocol {
    func testFunc (_ a: String, _ b: String? = nil)
}

So I understand that b can still be optional by the following declaration

protocol testProtocol {
    func testFunc (_ a: String, _ b: String?)
}

and my class can conform to this protocol:

class TestIt: testProtocol {
    func testFunc(_ a: String, _ b: String?) {
        print ("Do stuff with a and b")
    }
}

However I would like to call this function with the following declaration:

let test = TestIt()

    test.testFunc("a")

Inevitably this does not compile, and the solution seems to be

let test = TestIt()
test.testFunc("a", nil)

However passing nil to a function does not seem a very swifty way of doing things.

Note that this is a minimum example, is not production ready and is simply to identify a solution to the general problem of passing nil in a protocol.

Can I call testFunc without using nil?

Upvotes: 1

Views: 191

Answers (1)

user6907854
user6907854

Reputation:

You can do like this:

protocol TestProtocol {
    func testFunc (_ a: String, _ b: String?)
}

extension TestProtocol {
    func testFunc (_ a: String) {
        self.testFunc(a, nil)
    }
}

Upvotes: 6

Related Questions