Gotchas related to prefix +/- operators

Let's have a place to discuss issues related to prefix plus and prefix minus operators gotchas (unexpected behaviour) cause by prefix minus being parsed as part of the integer and float literal processing and due to other special treatments (like concrete overloads being preferred over generic overloads, etc). If you add an entry please specify whether it is compile time or run time (the latter is obviously more dangerous).

Even if we decide that the the existing state of affairs is ok with us this thread will raise awareness of the specific pitfalls and fewer people will get caught by surprise.

Run time gotchas:

Being runtime they are quite scary.




// Run time
let x: Int8 = -(-128)
// 🤔 somewhat unexpected that this compiles (crashes at runtime)


Compile time gotchas

Being compile time they are not so dangerous.

Would be a gotcha if "-" was parsed as an operator:



Other similar gotchas

Unrelated to prefix + / - operators specifically, but potentially to all prefix operators:


// Run time (not +/- specific, same issue)
let x = -42
    .addingReportingOverflow(42).partialValue
    // if you are unfamiliar this is same as + (almost)
print(x) // -84 🤔

// Compile time (not +/- specific, same issue)
let x: Int8 = -128.self // 🛑 Integer literal '128' overflows when stored into 'Int8'
3 Likes