Swift 中许多有的运算符,可以方便做一些运算操作。 例如:

  • 溢出运算符 &+= &-=
  • 范围运算符 ..< ...
  • 空合运算符 ?? 等等

那么,这些运算符的如何进行定义、优先级大小和结合性如何设置等等,让我们一起来了解一下吧!

如何定义运算符?

1
2
3
4
5
6
7
8
/// 前缀
prefix operator ++

/// 中缀
infix operator **

/// 后缀
postfix operator --

运算符的优先级

优先级组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//===----------------------------------------------------------------------===//
// Standard precedence groups
//===----------------------------------------------------------------------===//
precedencegroup AssignmentPrecedence {
assignment: true
associativity: right
}
precedencegroup FunctionArrowPrecedence {
associativity: right
higherThan: AssignmentPrecedence
}
precedencegroup TernaryPrecedence {
associativity: right
higherThan: FunctionArrowPrecedence
}
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
}

以上是 swift 源码中关于标准优先级组的定义。当然,我们也可以查看官方的文档了解运算符的优先级组。下表展示了优先级由低到高的排列

优先级

优先级(由低到高) 结合性 运算符
AssignmentPrecedence right *= &*= /= %= += &+= -= &-= <<= &<<= >>= &>>= &= ^= |=
FunctionArrowPrecedence right ~>
TernaryPrecedence right ?:
DefaultPrecedence none
LogicalDisjunctionPrecedence left ||
LogicalConjunctionPrecedence left &&
ComparisonPrecedence none < <= > >= == != === !== ~=
NilCoalescingPrecedence right ??
CastingPrecedence none is as as! as?
RangeFormationPrecedence none ... ..<
AdditionPrecedence left + &+ - &- | ^
MultiplicationPrecedence left * &* / % &
BitwiseShiftPrecedence none << &<< >> &>>
  • 中缀运算符默认的优先级别为 DefaultPrecedence
  • 中缀运算符默认的结合性为 none
  • DefaultPrecedence 的优先级高于 TernaryPrecedence

如何自定义运算符?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 1
precedencegroup PowerPrecedence {
associativity: left
higherThan: MultiplicationPrecedence
}

// 2
infix operator ** : PowerPrecedence

// 3
extension Int {
static func ** (lhs: Int, rhs: Int) -> Int {
return Int(pow(Double(lhs), Double(rhs)))
}
}
  1. 定义优先级组 PowerPrecedence,设置结合性为 left,优先级大于 MultiplicationPrecedence
  2. 定义运算符 **,设置优先级别为 PowerPrecedence
  3. 扩展 Int,添加**运算。