[swift-evolution] Proposal: Adding precedence option for prefix and postfix operators

Jason Nielsen drjdnielsen at gmail.com
Sat Jan 16 09:30:41 CST 2016

Hi all,

My proposal is to add a precedence option for prefix and postfix
operators.  It is great that swift allows for associativity and precedence
for binary operators but it hasn't quite gone all the way to make operator
overloading fully functional (just an opinion).  To illustrate consider the
following code:

import CoreFoundation

infix operator ** { associativity right precedence 200 }

func ** (base: Double, power: Double) -> Double {
    return pow(base, power)


which prints 9 and -9.  In the first case because unary minus has higher
precedence as a prefix operator it evaluates to (-3)*(-3) and the second
because - is viewed as a binary operator of lower precedence as (0-(3*3).
Exponentiation has higher precedence than subtraction so -3**2 should be -9
and the two expressions above are mathematically equivalent.  I originally
reported this as a bug (SR-552) as to me the point of operator overloading
is to allow you to write numerical expressions cleanly but should give you
the correct mathematical result.  The only really useful application I can
think of for operator overloading is basically as a DSL for numerical
expressions.  If it doesn't allow you to get correct results without having
to put brackets everywhere it sort of defeats the purpose (just my opinion
of course).

Best regards,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160116/e2376ba7/attachment.html>

More information about the swift-evolution mailing list