Search code examples
swiftinfix-notation

Why is `infix` the default


I'm reading about advanced operators in swift.

A basic function:

func add(a: Unicorn, b: Unicorn) -> Unicorn { return a + b }
add(u1, u2) // two unicorns are added

An infix operator:

func + (a: Unicorn, b: Unicorn) -> Unicorn { return a + b }
c = u1 + u2

postfix:

postfix func + (a: Unicorn) -> Unicorn { return a + 2 } // nonsense example
u1+

I don't understand how infix can be presumed to be the default. It doesn't look any different to me from a normal function declaration.

What is the rule here--is any single character a legal name for an infix operation? Does this mean single char functions are not otherwise allowed? Can any two-argument function in swift be called infix style?


Solution

  • I don't understand how infix can be presumed to be the default.

    If you implement an operator with two arguments the compiler can be sure you want an infix operator, because only infix operators operate on two values.

    If you implement an operator with one value the compiler isn't sure whether it is either an prefix or postfix operator and will complain.

    Infix operators take two values, postfix and prefix only one.

    Does this mean single char functions are not otherwise allowed? Can any two-argument function in swift be called infix style?

    No. A function that begins with any of these characters is an operator: /, =, -, +, !, *, %, <, >, &, |, ^, ?, or ~1. An operator can also consist of multiple characters, but it must begin with one of these characters.

    Remember that a new operator must be declared first, for instance like this:

    prefix operator / {}
    prefix func / (a: Int) -> Int {
        return a / 42
    }
    
    /56
    

    However this declaration won't work, because a is not one of the characters with which an operator must start:

    prefix operator a {}
    

    1 There are actually more characters. Read here.