[swift-evolution] [Discussion/Draft] Allow Precedence For Prefix And Postfix Operators

Daniel Duan daniel at duan.org
Sun Feb 28 19:25:34 CST 2016

Hi all,

I'd like to be able to specify precedence for custom pre/postfix operators.
What's your opinion? I'll let a draft of my proposal say the rest.


# Allow Specifying Precedence For Prefix And Postfix Operators

* Proposal: TBD
* Author(s): [Daniel Duan](https://github.com/dduan)
* Status: **Awaiting review**
* Review manager: TBD

## Introduction

Swift allows users to specify precedence for infix custom operators but not
for prefix and postfix operators. This Proposal extends prefix and postfix
operator declaration syntax to include a precedence specifier.

## Motivation

Operators compose expressions. Precedence affects the result of such
composition. Prefix and postfix operators are not different from infix
operator in this regard. Without the ability to specify a precedence, users
have to rely on understanding of default precedence value and parenthesis to
work with their costume prefix and postfix operators.

For example, user might need to extend the range operator `..<` to support
a `OpenRange` type, which represent a range with only one end specified with
an integer:

prefix operator ..< {}
prefix func ..<(end: Int) -> HalfRange { // … }

The user might want the following to mean `..< (someNumber + 3)` instead of
`(..< someNumber) + 3`, but they need the ability to say `..<` has higher
precedence than `+`.

let x = ..< someNumber + 3

Hence the need for enabling precedence specification for prefix and postfix

## Proposed solution

Modify syntax for specifying both prefix and postfix operators. Add the
*precedence* specifier, as it exists for infix operators.

## Detailed design

The Swift compiler will implement the updated prefix and postfix operation
declaration syntax as the following:
prefix-operator-declaration → prefix­operator­operator { [precedence-clause] }­
postfix-operator-declaration → prefix­operator­operator { [precedence-clause] }­

Omitting *precedence-clause* means giving the declared operator a default
precedence value.

## Impact on existing code

None. This change is purely additive.

## Alternatives considered


More information about the swift-evolution mailing list