﻿ Swift三元运算符编译错误 - 代码日志

Swift三元运算符编译错误

``````    let x = 5
let y = 4
var z:Int
x < 4 ? z = 6 : z = 8
``````

``````let x = 2 + 3
``````

``````let x = (2 + 3)
``````

``````(let x = 2) + 3
``````

``````x < 4 ? z = 6 : z = 8
``````

``````x...
x < ...
x < 4 // precedence 130, so resolves
(x < 4)...
(x < 4) ?...
(x < 4) ? z...
(x < 4) ? z = ... // Does not yet resolve. Why? Well, here, the ternary isn't
// really an infix. It is special kind of operator that
// takes something between ? and :. So normal associativity
// doesn't apply. (I'm still experimenting...)
(x < 4) ? z = 6 : ...
(x < 4) ? z = 6 : z // HERE it resolves. The z is grabbed, as the ternary has
// precedence 100, larger than the 90 precedence of the =
((x < 4) ? z = 6 : z) = 8
``````

``````if (x < 4) { z = 6 } else { z } = 8... // Compiler has a hissy fit
``````

``````x < 4 ? (z = 6) : (z = 8) // x < 4 ? z = 6 : (z = 8) works as well
``````

``````let z = x < 4 ? 6 : 8
let z...
let z = ...
let z = x ...
let z = x < 4 // < has precedence 130, bigger than =
let z = (x < 4) ? // ? has precedence of 100, bigger than =
let z = if (x < 4) { 6 } else { 8 }
``````

``````x < 4 ? z = 6 : (z = 8)
``````

``````let z = if (x < 4) { 6 } else { 8 }
``````