[swift-evolution] Postfix operators that start with ? or !

Toni Suter tonisuter at me.com
Tue Nov 1 09:23:32 CDT 2016


Hi,

In Swift 3, I can declare a postfix operator that starts with a ? or a !, but as far as I can tell, there's no way to actually use such an operator:

postfix operator ?**
postfix func ?**(x: Int) -> Int { return x }
let x = 12
x?**			// error: use of unresolved operator '**'

postfix operator !**
postfix func !**(x: Int) -> Int { return x }
let x = 12
x!**			// error: use of unresolved operator '**'

It makes sense to me, why that happens. There's no way for the parser to know, whether ?** is the end of an optional chaining expression
followed by a postfix operator ** or whether it's a single postfix operator ?**. Similarly, !** could refer to a forced-value expression followed
by a postfix operator ** or a single postfix operator !**.

Even with semantic knowledge, it is unclear, what should happen. For example, in the following situation either parsing decisions would
result in a valid program:

postfix operator ++
postfix operator ?++
postfix func ++(x: inout Int) {
    x += 1
}
postfix func ?++(x: Int?) -> Int? {
    return x
}
var x: Int? = 0
x?++		// what should happen here? Swift 3 chooses optional chaining expression followed by ++ operator

I think it would probably be best to disallow postfix operators that start with a question mark or an exclamation mark.
At the moment it is possible to declare them, but not to use them. That's not very user-friendly. 

By the way, infix operators have a similar problem. Infix operators that start with a ? or a ! must be surrounded by whitespace whereas
other infix operators don't have to be:

let x: Int? = 0
x ?? 10 	// fine
x??0 		// error
2 + 10		// fine
2+10		// fine

I think this is less of an issue, because you can at least use such infix operators if you add the necessary whitespace.

What do you think about this? Would it make sense to disallow postfix operators that start with a question mark or an exclamation mark?

Thanks and best regards,
Toni


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161101/de52a54f/attachment.html>


More information about the swift-evolution mailing list