Swift 操作符怎么用?

文章导读
Previous Quiz Next 操作符是用于对操作数执行操作的特殊符号。操作符可用于各种数学计算和逻辑操作。
📋 目录
  1. Swift 中的操作符是什么?
  2. Swift 操作符的类型
  3. Swift 算术操作符
  4. Swift 比较操作符
  5. Swift 逻辑运算符
  6. Swift 位运算符
  7. Swift 赋值运算符
  8. Swift 杂项运算符
  9. Swift 高级运算符
  10. Swift 运算符优先级
A A

Swift - 操作符



Previous
Quiz
Next

操作符是用于对操作数执行操作的特殊符号。操作符可用于各种数学计算和逻辑操作。

Swift 中的操作符是什么?

操作符是一个符号,它告诉编译器执行特定的数学或逻辑操作。或者可以说,操作符是用于在一或多个操作数之间执行特定操作的特殊符号。

例如,要将两个数字 34 和 21 相加,我们将使用 + 操作符 (34 + 21 = 55)。

Swift 操作符的类型

Swift 支持以下类型的操作符:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Range Operators
  • Misc Operators

我们将分别详细讨论每个操作符。

Swift 算术操作符

算术操作符用于对给定的操作数执行加法、除法、乘法等数学操作。它们总是对两个操作数进行操作,但这些操作数的类型必须相同。Swift 支持以下算术操作符:

操作符 名称 示例
+ Addition 20 + 30 = 50
- Subtraction 30 - 10 = 20
* Multiplication 10 * 10 = 100
/ Division 20 / 5 = 4
% Modulus 10 % 2 = 0

示例

使用算术操作符计算购买物品总费用的 Swift 程序。

import Foundation

let item1Price = 120
let item2Price = 80
let quantity1 = 2
let quantity2 = 3

let totalCostItem1 = item1Price * quantity1
let totalCostItem2 = item2Price * quantity2
let totalAmount = totalCostItem1 + totalCostItem2

print("Total cost of item 1: \(totalCostItem1)")
print("Total cost of item 2: \(totalCostItem2)")
print("Total bill amount: \(totalAmount)")

输出

Total cost of item 1: 240
Total cost of item 2: 240
Total bill amount: 480

Swift 比较操作符

比较操作符用于比较两个操作数并找出它们之间的关系。它们将结果返回为 boolean 值(true 或 false)。Swift 支持以下比较操作符:

操作符 名称 示例
(==) Equal 10 == 10 = true
!= Not Equal 34 != 30 = true
> Greater than 90 > 34 = true
< Less than 12 < 34 = true
>= Greater than or Equal to 30 >= 10 = true
<= Less than or Equal to 10 <= 32 = true

示例

使用比较操作符比较两部手机价格的 Swift 程序。

import Foundation

let pricePhoneA = 45000
let pricePhoneB = 50000

print("Phone A is cheaper than Phone B: \(pricePhoneA < pricePhoneB)")
print("Phone A and Phone B have the same price: \(pricePhoneA == pricePhoneB)")
print("Phone B is more expensive than Phone A: \(pricePhoneB > pricePhoneA)")

输出

Phone A is cheaper than Phone B: true
Phone A and Phone B have the same price: false
Phone B is more expensive than Phone A: true

Swift 逻辑运算符

逻辑运算符用于对给定的表达式执行逻辑运算。它还可以对多个条件进行决策。通常与 Boolean 值一起使用。Swift 支持以下逻辑运算符 −

运算符 名称 示例
&& Logical AND X && Y
|| Logical OR X || Y
! Logical NOT !X

示例

使用逻辑运算符根据年龄和收入检查用户是否符合贷款资格的 Swift 程序。

import Foundation

let age = 28
let monthlyIncome = 35000

let hasMinimumAge = age >= 21
let hasSufficientIncome = monthlyIncome >= 30000

if hasMinimumAge && hasSufficientIncome {
    print("Eligible for loan.")
} else {
    print("Not eligible for loan.")
}

// 使用 OR 和 NOT
let hasGoodCreditScore = false
if hasSufficientIncome || hasGoodCreditScore {
    print("Eligible based on income or credit score.")
}

print("Is NOT underage: \(!(age < 18))")

输出

Eligible for loan.
Eligible based on income or credit score.
Is NOT underage: true

Swift 位运算符

位运算符用于操作整数的单个位。它们通常用于执行位级运算。Swift 支持以下位运算符 −

运算符 名称 示例
& Bitwise AND X & Y
| Bitwise OR X | Y
^ Bitwise XOR X ^ Y
~ Bitwise NOT ~X
<< Left Shift X << Y
>> Right Shift X >> Y

示例

使用两个表示访问权限的整数值演示位运算的 Swift 程序。

import Foundation

let readPermission: UInt8 = 0b0001  // 1
let writePermission: UInt8 = 0b0010 // 2

let fullAccess = readPermission | writePermission
let hasRead = (fullAccess & readPermission) != 0
let hasWrite = (fullAccess & writePermission) != 0
let inverted = ~readPermission

print("Full access (read | write): \(fullAccess)")
print("Has read permission: \(hasRead)")
print("Has write permission: \(hasWrite)")
print("Inverted read permission: \(inverted)")

输出

Full access (read | write): 3
Has read permission: true
Has write permission: true
Inverted read permission: 254

Swift 赋值运算符

赋值运算符用于将新值赋值并更新给定变量的值。Swift 支持以下赋值运算符 −

运算符 名称 示例
(=) Assignment X = 10
+= Assignment Add X = X + 12
-= Assignment Subtract X = X - 12
*= Assignment Multiply X = X * 12
/= Assignment Divide X = X / 12
%= Assignment Modulus X = X % 12
<<= Assignment Left Shift X = X << 12
>>= Assignment Right Shift X = X >> 12
&= Bitwise AND Assignment X = X & 12
^= Bitwise Exclusive OR Assignment X = X ^12
|= Bitwise Inclusive OR Assignment X = X | 12

示例

使用赋值运算符计算并更新储蓄账户余额的 Swift 程序。

import Foundation

var savings = 10000

// 存款金额
savings += 5000  // 加 5000
print("After deposit, savings: \(savings)")

// 取款金额
savings -= 2000  // 减 2000
print("After withdrawal, savings: \(savings)")

// 应用 10% 利息
savings *= 110
savings /= 100
print("After applying interest, savings: \(savings)")

输出

After deposit, savings: 15000
After withdrawal, savings: 13000
After applying interest, savings: 14300

Swift 杂项运算符

除了通用运算符外,Swift 还支持一些特殊的运算符(杂项运算符),它们是 −

运算符 名称 示例
- 一元减号 -9
+ 一元加号 2
Condition ? X : Y 三元条件 如果 Condition 为 true ? 则值为 X : 否则值为 Y

示例

Swift 程序演示使用一元减号和加号调整温度,以及使用三元运算符检查温度是否舒适。

import Foundation

var currentTemperature = 25
let temperatureChange = -5

// 一元减号
let newTemperature = currentTemperature + (-temperatureChange)  // 增加 5 度
print("New Temperature: \(newTemperature) Degree Celsius")

// 一元加号
let adjustedTemperature = +newTemperature //无效果
print("Adjusted Temperature: \(adjustedTemperature) Degree Celsius")

// 使用三元运算符检查舒适度
let comfort = (adjustedTemperature >= 20 && adjustedTemperature <= 30) ? "Comfortable" : "Uncomfortable"
print("Temperature is: \(comfort)")

输出

New Temperature: 30 Degree Celsius
Adjusted Temperature: 30 Degree Celsius
Temperature is: Comfortable

Swift 高级运算符

除了基本运算符外,Swift 还提供了一些高级运算符,用于操作复杂值,它们是 −

  • Arithmetic Overflow Operators
  • Identity Operators
  • Range Operators

我们将详细讨论每个运算符。

Swift Arithmetic Overflow Operators

Arithmetic overflow operators 用于执行算术运算,并在发生溢出时很好地处理。或者说,这些运算符可以处理那些值可能超过最大或最小边界的整数。Swift 支持以下 arithmetic overflow operators −

运算符 名称 示例
&+ 溢出加法 Num1 &+ Num2
&- 溢出减法 Num1 &- Num2
&* 溢出乘法 Num1 &* Num2

Swift Identity Operators

Identity operators 用于判断给定的变量是否引用同一个实例。这些运算符与对象和 class 一起使用。它们是引用类型运算符。Swift 支持以下类型的 identity operators −

运算符 名称 示例
=== 相同于 Value1 === Value2
!== 不相同于 Value2 !== Value2

Swift Range Operators

Range operators 用于定义范围。它们用于循环、集合和控制流语句。Swift 支持以下 range operators −

运算符 名称 示例
XY 闭区间 1...3 = 1, 2, 3
X.. 半开区间 1..<3 = 1, 2
X... 或 ...X 单侧区间 2... = 2, 3, 4,

Swift 运算符优先级

运算符优先级决定了表达式中术语的分组。这会影响表达式的求值方式。某些运算符的优先级高于其他运算符;例如,乘法运算符的优先级高于加法运算符。

例如,x = 7 + 3 * 2; 这里,x 被赋值为 13,而不是 20,因为运算符 * 的优先级高于 +,所以先计算 3*2,然后加到 7 上。

在这里,优先级最高的运算符出现在表格顶部,优先级最低的出现在底部。在表达式中,优先级更高的运算符会先被求值。

名称 运算符 优先级
Primary Expression Operators () [] . expr++ expr-- left-to-right
一元运算符

* & + - ! ~ ++expr --expr

* / %

+ -

>> <<

< > <= >=

== !=

right-to-left
二元运算符 & ^ | && || left-to-right
三元运算符 ?: right-to-left
赋值运算符 (= += -= *= /= %= >>= <<= &= ^= |=) right-to-left
逗号 , left-to-right