[Pitch] Allow operator functions to have extra arguments with default values

Motivation

Currently, operator functions in Swift can only have exactly one or two arguments depending on the type of the operator.

This limitation can be relaxed to offer developers more flexibility, especially when additional parameters can be inferred or provided during function invocation.

For example, this can be used to add #file and #line defaults in the operator function for logging / testing / debugging purposes.

Proposed solution

We would lift the hard-coded limitation of argument count in operator functions. Here's an illustrative example:

infix operator <-
public func <- (lhs: T, rhs :T, file: StaticString = #file, date: Date = Date()) -> U { 
  // #file and Date() could be used for debugging purposes. 
}

When the proposal is accepted, an operator function would be allowed to have:

  • One or two main parameters without default values.
  • Any number of additional parameters, given that they all have default values.

There's a chance that this could be achieved with macros, in which case we could revert to using it. Still, providing this would offer more ease compared to setting up the macros.


A draft evolution proposal can be found here, with POC implementation

Related discussions:

13 Likes

Obviously very very very in favor of this. I don't use custom operators often, but every time I do I wish I had this.

7 Likes

Can you summarize the feedback given during these prior pitches, and does your current design address them?

2 Likes

There has been some discussion around this topic in another thread in a wider scope, i.e. supporting default parameters on getters, setters, operators, protocol requirements, ... But it stopped at some point without a real consensus.

2 Likes