Swift 3中改进了操作符的优先级及结合性的声明方式。

Swift 3之前,是使用magic numbers(魔数)的方式来声明操作符的优先级,如下代码所示:

infix operator <~ {
    associativity left
    precedence 125
}

magic numbers总归是一个不好的东西,所以Swift 3改用precedence groups(优先级组)的方式来声明操作符的优先级,如下代码所示:

precedencegroup Equivalence {
    associativity: left
    higherThan: LogicalConjunctionPrecedence
    lowerThan: ComparisonPrecedence
}

infix operator ~ : Equivalence

系统为我们提供了一些默认的precedence groups,如下代码所示:

precedencegroup AssignmentPrecedence {
  assignment: true
  associativity: right
}
precedencegroup TernaryPrecedence {
  associativity: right
  higherThan: AssignmentPrecedence
}
precedencegroup DefaultPrecedence {
  higherThan: TernaryPrecedence
}
precedencegroup LogicalDisjunctionPrecedence {
  associativity: left
  higherThan: TernaryPrecedence
}
precedencegroup LogicalConjunctionPrecedence {
  associativity: left
  higherThan: LogicalDisjunctionPrecedence
}
precedencegroup ComparisonPrecedence {
  higherThan: LogicalConjunctionPrecedence
}
precedencegroup NilCoalescingPrecedence {
  associativity: right
  higherThan: ComparisonPrecedence
}
precedencegroup CastingPrecedence {
  higherThan: NilCoalescingPrecedence
}
precedencegroup RangeFormationPrecedence {
  higherThan: CastingPrecedence
}
precedencegroup AdditionPrecedence {
  associativity: left
  higherThan: RangeFormationPrecedence
}
precedencegroup MultiplicationPrecedence {
  associativity: left
  higherThan: AdditionPrecedence
}
precedencegroup BitwiseShiftPrecedence {
  higherThan: MultiplicationPrecedence
}

参考

  1. Improved operator declarations