cast operator precedence


(Elena Vilchik) #1

Hello,

I've found here
<https://developer.apple.com/library/prerelease/ios/documentation/Swift/Reference/Swift_StandardLibrary_Operators/index.html#//apple_ref/doc/uid/TP40016054>
that "as" operator has a lower precedence than "*" operator (132 vs 160).
Why then this code compiles if multiplication should be made first?

var x = 1
print(x as Int * 100)

Conversely this code doesn't compile (as expected) - multiplication is made
first:

var x : Float = 1
print(100 * x as Int)

···

------
Elena Vilchik


(Jens Alfke) #2

“as ___” is a *postfix* operator (the following type name has to be considered part of the ‘as’.) So there’s only one way to parse that expression as valid Swift, and thus the parser doesn’t even have to look at operator precedence.

In other words, `x as (Int * 100)` isn’t valid Swift syntax, so the parser doesn’t even consider it.

—Jens

···

On Dec 4, 2015, at 3:21 AM, Elena Vilchik <vilchik.elena@gmail.com> wrote:

I've found here <https://developer.apple.com/library/prerelease/ios/documentation/Swift/Reference/Swift_StandardLibrary_Operators/index.html#//apple_ref/doc/uid/TP40016054> that "as" operator has a lower precedence than "*" operator (132 vs 160).
Why then this code compiles if multiplication should be made first?

var x = 1
print(x as Int * 100)


(Elena Vilchik) #3

Hello Jens,

Thanks for an answer. Anyway it's confusing to have this "as ___" operator
among infix operators
<https://developer.apple.com/library/prerelease/ios/documentation/Swift/Reference/Swift_StandardLibrary_Operators/index.html#//apple_ref/doc/uid/TP40016054>
and as binary-expression
<https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/swift/grammar/binary-expression>
.

···

2015-12-04 20:30 GMT+01:00 Jens Alfke <jens@mooseyard.com>:

On Dec 4, 2015, at 3:21 AM, Elena Vilchik <vilchik.elena@gmail.com> wrote:

I've found here
<https://developer.apple.com/library/prerelease/ios/documentation/Swift/Reference/Swift_StandardLibrary_Operators/index.html#//apple_ref/doc/uid/TP40016054>
that "as" operator has a lower precedence than "*" operator (132 vs 160).
Why then this code compiles if multiplication should be made first?

var x = 1
print(x as Int * 100)

“as ___” is a *postfix* operator (the following type name has to be
considered part of the ‘as’.) So there’s only one way to parse that
expression as valid Swift, and thus the parser doesn’t even have to look at
operator precedence.

In other words, `x as (Int * 100)` isn’t valid Swift syntax, so the parser
doesn’t even consider it.

—Jens