Why are default arguments not allowed in protocols?

I like that default keyword as part of the protocol requirements. Should be worth pitching.

As it seems to work and answers the original question, is this still the way to do it or is there something better now?

It’s still the way.

1 Like

Resurrecting this thread - I wonder if we could just have default arguments be sugar for the compiler adding the extension :thinking:

Would be a nice UX win for protocols IMO

What if conforming implementations were required to use the default values specified in a protocol? One could then write something like:

protocol Foo {
	func foo_defaut_value(param: Int = 123)
}

struct Bar: Foo {
	// func foo_defaut_value(param: Int = default) {  }
}

The = default indicates that the default value is inherited, not added or overridden in any way. This restriction would mean existentials and conforming types always have the same default values, making them easier to reason about from the caller’s point of view.

However, this might break code where a subclass uses different default values from its superclass.

I don’t know that there’s a good solution for that. It might even be necessary to disallow cases where the default values in both protocols match, since a change in either protocol would prevent conforming to both (if default values are selected statically—Swift’s current behavior).

2 Likes

If you have multiple arguments, on way to do this is using a struct as argument mix with what @mayoff proposed.

This could look like :

public struct MyFuncParameters {
    var arg: Int
    var arg2: Double

    public static func `for` (arg: Int = 1, arg2: Double = 2.0) -> MyFuncParameters {
        return MyFuncParameters(arg: arg, arg2: arg2)
    }
}

protocol A {
    func myFunc(_ parameters: MyFuncParameters)
}

a.myFunc(.for(arg: 2))