【发布时间】:2016-07-19 02:24:42
【问题描述】:
我无法理解三元运算符上下文中的关联性概念。在大多数情况下,三元运算符如下所示:
a ? b : c
在这种情况下,不需要关联性来评估表达式。但有时,三元运算符是嵌套的:
a ? b : c ? d : e
a ? b : (c ? d : e) // : is right-associative
不过嵌套也可以倒置
a ? b ? c : d : e
a ? (b ? c : d) : e // : is left-associative
解释这种现象的最佳方法是什么?您能否认为 : 运算符的关联性取决于上下文,还是我在这里遗漏了什么?
当人们想要定义自己的三元运算符时,关联性问题就变得相关了,例如在 Swift 中:
infix operator ? { associativity right precedence 120 }
infix operator : { associativity left precedence 130 }
【问题讨论】:
标签: swift operators ternary-operator associativity