Swift: which has higher precedence, prefix or postfix operator?

Derrick Ho
1 min readSep 26, 2017
prefix operator ++prefix func ++(lhs: String) -> String {
return lhs + "pre"
}
postfix operator ++postfix func ++(rhs: String) -> String {
return rhs + "post"
}
var n = "0"++n++ // What will this print?

What does ++n++ create? Before you read the article for the answer or try it out in playgrounds, leave a comment down below with your answer!

Coming from a C/C++ background we had ++ and -- as prefix and postfix operators. I was taught that prefix operators are applied to the expression then the expression was delivered to a function, then when that was over, the postfix operator would apply.

#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << ++n++;
cout << n;
return 0;
}

What would be the result of this?

My first guess would be “12” since it would increment n to 1 then pass that value to cout. Then n gets incremented to “2” so the second cout would recieve 2.

This stackoverflow entry seems to support my theory:

int n = 2;
cout << n++ << " " << ++n << " " << n++ << " " << ++n << " " << n++;

However, when I tried ++n++ it actually doesn’t compile…

My memory must be pretty fuzzy since I thought it did.

Let get back to the swift question I had in the beginning of the article.

++n++ gives you “0postpre”

--

--